toLocaleDateString() is subtracting a day

后端 未结 1 676
猫巷女王i
猫巷女王i 2021-01-17 14:07

I\'m pulling dates from a SQL database which treats them as dates that start at midnight. When I go to use toLocaleDateString() on them, it formats them properl

1条回答
  •  有刺的猬
    2021-01-17 14:46

    If you run the code in pieces, you'll notice that new Date('2011-09-01T00:00:00') produces output like Wed Aug 31 2011 20:00:00 GMT-0400 (EDT) (my computer is in EDT right now).

    This is because (doc):

    Differences in assumed time zone

    Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted (this behavior is changed in ECMAScript ed 6 so that both will be treated as local).

    Converting that to the locale date string will convert it to a string appropriate for the browser's locale. Documentation indicates that "the default is the runtime's default time zone".

    If you want to ensure the string is in UTC time, use

    new Date('2011-09-01T00:00:00').toLocaleDateString('en-US', {timeZone: 'UTC'})
    

    0 讨论(0)
提交回复
热议问题