javascriptdate

Is the Javascript date object always one day off?


In my Javascript app I have the date stored in a format like so:

2011-09-24

Now when I try using the above value to create a new Date object (so I can retrieve the date in a different format), the date always comes back one day off. See below:

var date = new Date("2011-09-24");
console.log(date);

logs:

Fri Sep 23 2011 20:00:00 GMT-0400 (Eastern Daylight Time)

Solution

  • Notice that Eastern Daylight Time is -4 hours and that the hours on the date you're getting back are 20.

    20h + 4h = 24h
    

    which is midnight of 2011-09-24. The date was parsed in UTC (GMT) because you provided a date-only string without any time zone indicator. If you had given a date/time string w/o an indicator instead (new Date("2011-09-24T00:00:00")), it would have been parsed in your local timezone. (Historically there have been inconsistencies there, not least because the spec changed more than once, but modern browsers should be okay; or you can always include a timezone indicator.)

    You're getting the right date, you just never specified the correct time zone.

    If you need to access the date values, you can use getUTCDate() or any of the other getUTC*() functions:

    var d,
      days;
    d = new Date('2011-09-24');
    days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
    console.log(days[d.getUTCDay()]);