Skip to content Skip to sidebar Skip to footer

Javascript Date String Constructing Wrong Date

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 d

Solution 1:

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 = newDate('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 = newDate(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

Solution 2:

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. ;)

Solution 3:

Remove the prepending zero from "05"

Post a Comment for "Javascript Date String Constructing Wrong Date"