I am using the date input type to display/get dates from a form in HTML:
<input type="date">
To set the date from JavaScript I do:
myInput.valueAsDate = new Date();
This works fine. But if I want to set another date object, for example:
myInput.valueAsDate = new Date(1995, 0, 1);
It displays 12/31/1994
–which is exaclty one day before the 1995 New Year eve. If I add 24
as hours argument, the date is displayed correctly, but the date object itself is obviously 2nd of January, 1995, which is not a good solution to this problem.
console.log(myInput.valueAsDate = new Date(1995, 0, 1));
console.log(myInput.valueAsDate);
<input type="date" id="myInput">
I get this in the console:
Sun Jan 01 1995 00:00:00 GMT+0200 (EET)
Sat Dec 31 1994 02:00:00 GMT+0200 (EET)
Is this a browser issue? Are there any workarounds/solutions?
And finally, I do not want to use any plugin to display/get the dates but I want to use the natative date input
element (at least, the question is about it :-)
).
I reproduced this in Chromium and Chrome. Firefox seems not to support the date type inputs yet.
It's the timezone difference read this.
Apparently when using new Date()
you use the current time zone and valueAsDate
takes a GMT dateTime
Changing you code to something like this
console.log(myInput.valueAsDate = new Date(1995, 0, 1,12));
should work
Update 1
console.log(myInput.valueAsDate = new Date(Date.UTC(1995, 0, 1));
Should work on all timezones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With