Variable from form to Javascript - javascript

I try to get variable from a form to add dates to current date. I get the number, but the outcome date is way off. If I hardcore the number it works fine and when I try to display the variable it gets right.
Why does it not display the right date?
$("input[name='newDate']").on('ifClicked',function addDays(date,days) {
var today = new Date();
var numberOfDaysToAdd = this.value;
today.setDate(today.getDate() + (numberOfDaysToAdd));
alert(today +'value: ' + numberOfDaysToAdd);
});

I try to get variable from a form to add dates to current date. I get the number, but the outcome date is way off
Use parseInt();. I think you are trying to add a string value to the date and it is messing up. Parsing it to integer might help.
parseInt("12",10) if your input value is 12.
So use the below code.
var today = new Date();
var numberOfDaysToAdd = parseInt(this.value,10); //parse to Integer
today.setDate(today.getDate() + (numberOfDaysToAdd));
alert(today + 'value: ' + numberOfDaysToAdd);

Related

Past 2hours date and Time in IST Format javascript

I know that
var currentTime = new Date();
var currentOffset = currentTime.toISOString();
will give current date & time in IST format. Can anyone help me how to get past 2 hours date & time in IST format
To calculate a time difference, you can use a combination of the relevant get and set methods. After you get the value, you perform the desired calculation and use the result as the argument for the set.
Note that the default timezone is based on system settings. So performing such a change has no bearing on the timezone (i.e. for me the code outputs in PDT).
var time = new Date();
var currentOffset = time.getTimezoneOffset();
console.log('Current time: ' + time.toISOString());
console.log('Current offset: ' + currentOffset);
time.setHours(time.getHours() - 2);
var pastOffset = time.getTimezoneOffset();
console.log('Past time: ' + time.toISOString());
console.log('Past offset: ' + currentOffset);

Date.UTC() gets value null

From Server I get Date in UTC format like ,
2016-04-13T02:37:13.211316121-04:00
When I use this to display using new Date(data.Created_at) I get 7 min time difference. Like as I am displaying my date in format {{my_date | date: 'h:mm a'}}, insted showing 12:05 PM, it dispalys 11:58 AM. So I tried this,
data.Created_at = new Date(Date.UTC(data.Created_at))
which returns null value. Is there any problem in my code? How should I get perfect date?
If you check syntax of Date.UTC,
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
It expects value in different variables and not in date string. You can split it and manually parse it.
You can try something like this:
JSFiddle
var d = "2016-04-13T02:37:13.211316121-04:00";
var date_arr = d.split(/[-|T|\.|:]/);
var o = new Date(Date.UTC(date_arr[0], date_arr[1], date_arr[2], date_arr[3], date_arr[4], date_arr[5]));
console.log(date_arr, o);
Also, it gives me 8:07 AM, considering the time is 2:37 and my timezone is +5:30.
Use it like this
Date.UTC(year,month,day,hours,minutes,seconds,millisec)
The code you are using is invalid way to handle date. You can use this code
new Date('2016-04-13T02:37:13.211316121-04:00').toISOString();
var created_at = new Date(createdAt);
var created_at_date = (created_at.getUTCMonth()+1) + "/" + created_at.getUTCDate() + "/" + created_at.getUTCFullYear() + "/" + created_at.getHours() + ":"
+ created_at.getMinutes() + ":" + created_at.getSeconds();
Hope this will work for you!!!

Javascript date to sql date object

I'm trying to write a query that takes a Javascript date object and then puts it in an object type that is recognized by both SQL Server and Oracle database types.
The issue is that I'm using webservices. So it has to be a string, not an actual passed parameter. Here's what I mean:
var date = new Date();
var firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var webServicesQueryWhereClause = 'readDate BETWEEN '+firstDayOfMonth+' AND '+lastDayOfMonth;
Except firstDayOfMonth and lastDayOfMonth are surrounded by something like to_date() to actually put them in a date format that the databases can read. For example:
var webServicesQueryWhereClause = 'readDate BETWEEN to_date('+firstDayOfMonth+') AND to_date('+lastDayOfMonth+') ';
What should I use to put those dates in a form that can be read by both SQL Server and Oracle?
Have you tried the solutions presented here:
Convert JS date time to MySQL datetime
The title should be called
"Convert JS date to SQL DateTime"
I happened to need to do the same thing as you just now and I ran across this after your question.
This is from the other post by Gajus Kuizinas for those who want the answers on this page:
var pad = function(num) { return ('00'+num).slice(-2) };
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
pad(date.getUTCMonth() + 1) + '-' +
pad(date.getUTCDate()) + ' ' +
pad(date.getUTCHours()) + ':' +
pad(date.getUTCMinutes()) + ':' +
pad(date.getUTCSeconds());
or
new Date().toISOString().slice(0, 19).replace('T', ' ');
The first one worked for me. I had a reference problem with the toISOString as well although I would prefer the one liner. Can anyone clarify how to use it and know the limitations on where one can reference it?
Good luck!
using MomentJs it will be pretty easy.
moment().format('YYYY-MM-DD HH:mm:ss')
https://momentjs.com/
In my case I was trying to get a TIMESTAMP and store it to a variable so I can pass that array inside a SQL query(Row insertion)
The following worked for me quite well.
var created_at = new Date().toISOString().slice(0, 19).replace('T', ' ');
Maybe I found a bit shorter approach - tested on MSSQL and Postgres
const date = (new Date()).toLocaleString("en-US")
Enjoy!
I use:
const datetimeSQL = new Date().toISOString().split('T').join(' ').split('Z').join('');
// return '2022-09-02 19:54:17.028'

pre-populating date input field with Javascript

I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:
<html>
...
<input id='date' type='date'>
...
</html>
<script>
...
var myDate = new Date();
$("#date").val(myDate);
...
I have also tried passing the date object as a string
var myDate = new Date().toDateString();
$("#date").val(myDate);
When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.
Thanks.
It must be set in ISO-format.
(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
field.value = date;
console.log(field.value);
})()
http://jsfiddle.net/GZ46K/
Why Not to Use toISOString()
The <input type='date'> field takes a value in ISO8601 format (reference), but you should not use the Date.prototype.toISOString() function for its value because, before outputting an ISO8601 string, it converts/represents the date/time to UTC standard time (read: changes the time zone) (reference). Unless you happen to be working in or want that time standard, you will introduce a bug where your date will sometimes, but not always, change.
Populate HTML5 Date Input from Date Object w/o Time Zone Change
The only reliable way to get a proper input value for <input type='date'> without messing with the time zone that I've seen is to manually use the date component getters. We pad each component according to the HTML date format specification (reference):
let d = new Date();
let datestring = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
document.getElementById('date').value = datestring;
/* Or if you want to use jQuery...
$('#date').val(datestring);
*/
<input id='date' type='date'>
Populate HTML5 Date & Time Fields from Date Object w/o Time Zone Change
This is beyond the scope of the original question, but for anyone wanting to populate both date & time HTML5 input fields from a Date object, here is what I came up with:
// Returns a 2-member array with date & time strings that can be provided to an
// HTML5 input form field of type date & time respectively. Format will be
// ['2020-12-15', '01:27:36'].
function getHTML5DateTimeStringsFromDate(d) {
// Date string
let ds = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
// Time string
let ts = d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
// Return them in array
return [ds, ts];
}
// Date object
let d = new Date();
// Get HTML5-ready value strings
let dstrings = getHTML5DateTimeStringsFromDate(d);
// Populate date & time field values
document.getElementById('date').value = dstrings[0]
document.getElementById('time').value = dstrings[1]
/* Or if you want to use jQuery...
$('#date').val(dstrings[0]);
$('#time').val(dstrings[1]);
*/
<input type='date' id='date'>
<input type='time' id='time' step="1">
Thank you j08691. That link was the answer.
To others struggling like me, when they say input is "yyyy-mm-dd" the MEAN it!
You MUST have 4 digits for the year.
You MUST have a dash and no spaces.
You MUST have 2 digits for day and month.
In my example myDate.getMonth for January would only return "1" (actually it returns "0" because for some reason javascript counts months from 0-11). To get this right I had to do the following:
var myDate, day, month, year, date;
myDate = new Date();
day = myDate.getDate();
if (day <10)
day = "0" + day;
month = myDate.getMonth() + 1;
if (month < 10)
month = "0" + month;
year = myDate.getYear();
date = year + "-" + month + "-" + day;
$("#date").val(date);
I hope this helps others not waste hours like I did testing this before October or before the 10th of the month! LOL
Here is an answer based on Robin Drexlers but in local time.
//Get the local date in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 10);
//Set the field value
var field = document.querySelector('#date');
field.value = datestr;
If it's a datetime field you're modifying (as opposed to just the date) don't forget to add the time T00:00, or change the substring to 16 characters for example:
//Get the local date and time in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 16);
//Set the field value
var field = document.querySelector('#datetime');
field.value = datestr;
This below code populates the local date . The accepted answer populates UTC date.
var date = new Date();
field = document.querySelector('#date-id');
var day = date.getDate();
if(day<10){ day="0"+day;}
var month = date.getMonth()+1;
if(month<10){ month="0"+month;}
field.value = date.getFullYear()+"-"+month+"-"+day;
I don't have the reputation points to comment on another answer, so I'll just add a new answer. And since I'm adding an answer, I'll give more details than I would've in a comment.
There's an easier way to zero pad than all of the juggling that everyone is doing here.
var date = new Date();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var year = date.getFullYear();
var htmlDate = year + '-' + month + '-' + day;
console.log("Date: " + htmlDate);
Today, the output would be
Date: 2020-01-07
The code is building a dynamic string by prepending a quoted zero, then taking the last 2 characters with slice(-2). This way, if the zero makes it 01, the last 2 are 01. If the zero makes it 011, then the last two are 11.
As for the month starting at zero silliness, you can also add 1 dynamically before prepending the zero and everything still works. You just have to do the math operation before turning it into a string.
As a side note, I've noticed that when you update a date field, you have to hide the field before setting the value and show it after setting. I don't do this often enough, so I have to re-struggle each time I need to deal with it. Hopefully this will help someone from the future.
waves to future people

Adobe Pro, PDF form with javascript

I have created a form in Adobe Pro and i have added some JavaScript to it. But i have two problems.
1) Is there a "Document Finished Loading"-action? I have a date field on the form and i would like that it automatically adds todays date into that field when the user opens the document to fill in the form fields.
2) The date method that i am using doesn't work properly, i have this code:
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth();
var year = dt.getFullYear();
var dagensdatum = year + "-" + month + "-" + day;
var datum = this.getField("Datum");
datum.value = dagensdatum;
datum = this.getField("Datum2");
datum.value = dagensdatum;
datum = this.getField("Datum3");
datum.value = dagensdatum;
But when i run this, it prints out 11th of April and not todays date. Any ideas?
for your 2nd question I don't know why the date is not correct, but at least, you should do this :
var month = dt.getMonth();
month++;
because the getMonth() returns an int between 0 and 11. As for the day, I don't know what could cause the problem.
Edit : Have you checked your own date on your computer? Because if it is wrong it will be displayed uncorrectly in your browser. I guess you should have a date of 11th May in your computer, don't you?

Categories

Resources