javascript日期时区问题 [英] javascript Date timezone issue

查看:117
本文介绍了javascript日期时区问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个日期和年份的指定值的js Date对象。我会期待
新的日期(2000-01-01)给我的Date对象与2000为$ getFullYear() ,但如果我的电脑的时间设置设置为芝加哥时区,我将获得 Fri Dec 31 1999 18:00:00 GMT-0600(CST),对于布宜诺斯艾利斯: 1999年12月31日星期五22:00:00 GMT-0200(ARST)

I need a js Date object with specified values for date and year. I would expect new Date("2000-01-01") to give me Date object with 2000 as value for getFullYear(), but if my computer's time settings are set to Chicago timezone, I'm getting Fri Dec 31 1999 18:00:00 GMT-0600 (CST), and for Buenos Aires: Fri Dec 31 1999 22:00:00 GMT-0200 (ARST).

有没有办法创建Date对象,使用 .getFullYear()返回我们在构造函数中设置的日期,无论用户的机器上设置了什么时区?

Is there a way to create Date object, with .getFullYear() returning the date we set in constructor, no matter what timezone is set on user's machine?

更新:
我需要这个Date对象用于另一个库(调用它的 .getFullYear()方法,所以使用UTC getter不是真的有帮助。

Update: I need this Date object to be used in another library (which calls its .getFullYear() method, so using UTC getters doesn't really help.

推荐答案

解析一个字符串到一个 在JavaScript中, YYYY-MM-DD 格式的值被解释为UTC的值,而不是一个本地时间的价值。

When parsing a string to a Date in JavaScript, a value that is in YYYY-MM-DD format is interpreted as a UTC value, rather than a local-time value.

关键是零件分开b y连字符,并且字符串中没有时区信息。 ECMAScript 5.1规范在§15.9.1.15中说明:

The key is that the parts are separated by hyphens, and that there is no time zone information in the string. The ECMAScript 5.1 Spec says in §15.9.1.15:


...缺席时区偏移量的值为Z。

... The value of an absent time zone offset is "Z".

这意味着,如果你没有指定一个偏移量,那将会假定你是UTC。

That means, if you don't specify an offset, it will assume you meant UTC.

与ISO-8601所说的相反,这是ECMAScript 2015(6.0)中的行为已经改变,在§20.3.1.16

Note that since this is the opposite of what ISO-8601 says, this is behavior has been changed in ECMAScript 2015 (6.0), which says in §20.3.1.16:


...如果时区偏移不存在,则日期时间被解释为本地时间。

... If the time zone offset is absent, the date-time is interpreted as a local time.

因此,当ES6的这一规定正确实现,以前被解释为UTC的格式的字符串值将被解释为本地时间。我已经在这个这里上发表了博文。

Therefore, when this provision of ES6 is implemented properly, string values of this format that used to be interpreted as UTC will be interpreted as local time instead. I've blogged about this here.

解决方法很简单。用斜线代替连字符:

The workaround is simple. Replace the hyphens with slashes:

var s = "2000-01-01";
var dt = new Date(s.replace(/-/g, '/'));

或者,考虑像 moment.js ,这更加明智。

Alternatively, consider a library like moment.js which is much more sensible.

var s = "2000-01-01";
var dt = moment(s, 'YYYY-MM-DD').toDate();

这篇关于javascript日期时区问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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