Is the Javascript date object always one day off?

后端 未结 23 2651
既然无缘
既然无缘 2020-11-22 01:49

In my Java Script 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 obje

23条回答
  •  不知归路
    2020-11-22 02:27

    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()]);
    

提交回复
热议问题