Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date string constructing wrong date [duplicate]

Hi I am trying to construct a javascript date object with a string, but it keeps contructing the wrong day. It always constructs a day that is one day behind. Here is my code

var date = new Date('2006-05-17');

The date i want to get is

Wednesday May 17 2006 00:00:00 GMT-0700 (PDT)

But instead I get

Tue May 16 2006 17:00:00 GMT-0700 (PDT)
like image 992
user2158382 Avatar asked Sep 12 '13 21:09

user2158382


2 Answers

When you pass dates as a string, the implementation is browser specific. Most browsers interpret the dashes to mean that the time is in UTC. If you have a negative offset from UTC (which you do), it will appear on the previous local day.

If you want local dates, then try using slashes instead, like this:

var date = new Date('2006/05/17');

Of course, if you don't have to parse from a string, you can pass individual numeric parameters instead, just be aware that months are zero-based when passed numerically.

var date = new Date(2006,4,17);

However, if you have strings, and you want consistency in how those strings are parsed into dates, then use moment.js.

var m = moment('2006-05-17','YYYY-MM-DD');
m.format(); // or any of the other output functions
like image 139
Matt Johnson-Pint Avatar answered Sep 21 '22 10:09

Matt Johnson-Pint


What actually happens is that the parser is interpreting your dashes as the START of an ISO-8601 string in the format "YYYY-MM-DDTHH:mm:ss.sssZ", which is in UTC time by default (hence the trailing 'Z').

You can produce such dates by using the "toISOString()" date function as well. http://www.w3schools.com/jsref/jsref_toisostring.asp

In Chrome (doesn't work in IE 10-) if you add " 00:00" or " 00:00:00" to your date (no 'T'), then it wouldn't be UTC anymore, regardless of the dashes. ;)

like image 31
James Wilkins Avatar answered Sep 22 '22 10:09

James Wilkins