Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the date in date field sets it with one day before [duplicate]

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.

like image 989
Ionică Bizău Avatar asked Oct 06 '15 14:10

Ionică Bizău


1 Answers

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.

like image 60
Bobby Tables Avatar answered Oct 29 '22 15:10

Bobby Tables