8

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.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

1 Answers1

8

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.

Bobby Tables
  • 2,953
  • 7
  • 29
  • 53
  • Oh, good point! For posterity, could you post a reference how to transform a date in GMT date time? – Ionică Bizău Oct 06 '15 at 14:27
  • 1
    Also, is there any way to ignore the timezone somehow? I would like to just display the date from the date object. – Ionică Bizău Oct 06 '15 at 14:28
  • 1
    Will `new Date(1995, 0, 1,12)` work over the globe in all timezones? – Ionică Bizău Oct 06 '15 at 14:33
  • @IonicăBizău i don't think you can ignore the timezones. But if you create it with just `new Date()` your users will get their current date which is ok. If you get it from a server and you site is global you should care about timezones. so it's working as expected and maybe you shouldn't be searching for a workaround. – Bobby Tables Oct 06 '15 at 14:59
  • 1
    I guess the `Date.UTC` thingy is a nice solution. Thanks. :) – Ionică Bizău Oct 06 '15 at 15:05