Javascript 日期对象总是休息一天吗? [英] Is the Javascript date object always one day off?
问题描述
在我的 Java Script 应用程序中,我以如下格式存储日期:
In my Java Script app I have the date stored in a format like so:
2011-09-24
现在,当我尝试使用上述值创建一个新的 Date 对象(以便我可以以不同的格式检索日期)时,该日期总是会在休息日返回.见下文:
Now when I try using the above value to create a new Date object (so I can retrieve the date in a different format), the date always comes back one day off. See below:
var doo = new Date("2011-09-24");
console.log(doo);
日志:
Fri Sep 23 2011 20:00:00 GMT-0400 (Eastern Daylight Time)
推荐答案
请注意东部夏令时间为 -4 小时
,并且您返回日期的时间为 20
.
Notice that Eastern Daylight Time is -4 hours
and that the hours on the date you're getting back are 20
.
20h + 4h = 24h
这是 2011-09-24 的午夜.日期在 UTC (GMT) 中被解析,因为您提供了一个没有任何时区指示器.如果您提供了一个没有指示符的日期/时间字符串(new Date("2011-09-24T00:00:00")
),它将在您的本地时区中进行解析.(历史上一直存在不一致,尤其是因为规范更改了不止一次,但现代浏览器应该没问题;或者您始终可以包含时区指示器.)
which is midnight of 2011-09-24. The date was parsed in UTC (GMT) because you provided a date-only string without any time zone indicator. If you had given a date/time string w/o an indicator instead (new Date("2011-09-24T00:00:00")
), it would have been parsed in your local timezone. (Historically there have been inconsistencies there, not least because the spec changed more than once, but modern browsers should be okay; or you can always include a timezone indicator.)
您得到了正确的日期,只是您从未指定正确的时区.
You're getting the right date, you just never specified the correct time zone.
如果您需要访问日期值,您可以使用 getUTCDate()
或 任何其他 getUTC*()
函数:
If you need to access the date values, you can use getUTCDate()
or any of the other getUTC*()
functions:
var d,
days;
d = new Date('2011-09-24');
days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
console.log(days[d.getUTCDay()]);
这篇关于Javascript 日期对象总是休息一天吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!