javascript - toLocaleDateString() 是减去一天

标签 javascript sql

我从 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/

相关文章:

mysql - mysql如何垂直求和?

javascript - 在 Django 中设置当前导航菜单项的样式

javascript - 函数的__proto__

php - INSERT INTO 如果条件满足

c# - 哪个ORM支持多行更新和删除

sql - 将两个子查询的结果除以条件 where

sql - 如何获得SQLite中X列与Y列的比率?

javascript - Javascript Class.create() 表示类未定义

javascript - 删除单链表javascript中的节点

javascript - 转换数据:image/png;base64 into an image type in database