toLocaleDateString()减去一天 [英] toLocaleDateString() is subtracting a day

查看:56
本文介绍了toLocaleDateString()减去一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从SQL数据库中提取日期,该日期将其视为从午夜开始的日期.当我去在它们上使用 toLocaleDateString()时,它会正确格式化它们,但是在丢掉一天之前是不会的.

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 properly, however not before losing a day.

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

格式化后: 8/31/2011

代码:

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

为什么要这样做,我可以进行哪些行内修复以使其表现正常?我还发现了另一种出现类似问题的帖子,但我不是100%确信这是时区问题.

Why does it do this, and what inline fix can I make to have it behave properly? I also found another post that had a similar problem, but I'm not 100% convinced that it's a timezone issue.

推荐答案

如果分段运行代码,则会注意到 new Date('2011-09-01T00:00:00')产生类似 Wed Aug 31 2011 20:00:00 GMT-0400(EDT)的输出(我的计算机现在处于EDT中).

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).

这是因为( doc ):

假定时区的差异

给出日期字符串"2014年3月7日",parse()假定为本地时间区域,但考虑到ISO格式(例如"2014-03-07"),它将采用UTC时区.因此,使用这些字符串生成的Date对象将代表不同的时间,除非系统设置为UTC的本地时区.这意味着出现两个日期字符串等效格式可能会导致两个不同的值,具体取决于格式转换的字符串(此行为在ECMAScript ed 6,以便将两者都视为本地).

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".

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

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

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

这篇关于toLocaleDateString()减去一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆