gpt4 book ai didi

javascript - toLocaleDateString() 是减去一天

转载 作者:数据小太阳 更新时间:2023-10-29 04:56:21 26 4
gpt4 key购买 nike

我从 SQL 数据库中提取日期,该数据库将它们视为从午夜开始的日期。当我对它们使用 toLocaleDateString() 时,它会正确格式化它们,但不会在损失一天之前。

格式化前:2011-09-01T00:00:00

格式化后:8/31/2011

代码:

plan.dateReceived = new Date(plan.dateReceived).toLocaleDateString()+','+plan.dateReceived;

为什么它会这样做,我可以进行哪些内联修复以使其正常运行?我还找到了another post that had a similar problem , 但我不是 100% 相信这是时区问题。

最佳答案

如果您分段运行代码,您会注意到 new Date('2011-09-01T00:00:00') 产生类似 Wed Aug 31 2011 20 的输出: 00:00 GMT-0400 (EDT)(我的电脑现在处于美国东部时间)。

这是因为(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).

将其转换为语言环境日期字符串会将其转换为适合浏览器语言环境的字符串。 Documentation表示“默认是运行时的默认时区”。

如果要确保字符串是 UTC 时间,请使用

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

关于javascript - toLocaleDateString() 是减去一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32877278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com