Is the Javascript date object always one day off?

后端 未结 23 2331
既然无缘
既然无缘 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:24

    Trying to add my 2 cents to this thread (elaborating on @paul-wintz answer).

    Seems to me that when Date constructor receives a string that matches first part of ISO 8601 format (date part) it does a precise date conversion in UTC time zone with 0 time. When that date is converted to local time a date shift may occur if midnight UTC is an earlier date in local time zone.

    new Date('2020-05-07')
    Wed May 06 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
    

    If the date string is in any other "looser" format (uses "/" or date/month is not padded with zero) it creates the date in local time zone, thus no date shifting issue.

    new Date('2020/05/07')
    Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
    new Date('2020-5-07')
    Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
    new Date('2020-5-7')
    Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
    new Date('2020-05-7')
    Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
    

    So then one quick fix, as mentioned above, is to replace "-" with "/" in your ISO formatted Date only string.

    new Date('2020-05-07'.replace('-','/'))
    Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
    

提交回复
热议问题