javascript新Date()构造函数对相同的不同格式字符串的歧义行为 [英] Ambiguous behavior of javascript new Date() constructor for same different formatted string
问题描述
我的本地时区是(UTC + 06:00)达卡
.在我自己的时区,我没有发现此问题.但是在我的电脑中,将时区更改为(UTC -12:00)International Date Line West
My local time zone is (UTC+06:00) Dhaka
. In my own time zone I didn't find this problem. But changing the time zone to (UTC -12:00) International Date Line West
in my pc,
new Date(["2014","01","01"])
给我输出 2014年1月1日星期三00:00:00 GMT-1200(GMT-12:00)
.
新日期("2014-01-01")
给我输出 2013年12月31日星期二12:00:00 GMT-1200(GMT-12:00)
.
为什么会这样? ["2014","01","01"]
和"2014-01-01"
不应该提供相同的输出吗?
Why this is happening?
Shouldn't ["2014","01","01"]
and "2014-01-01"
suppose to give same output?
推荐答案
这是由于通过日期解析创建了 new Date("2014-01-01")
所引起的,该解析将日期视为设为UTC,然后应用时区,但将 new Date(["2014","01","01","01"])
视为您时区的构造函数中每个参数的文字值.尽管如以下注释之一所述,格式 new Date(["2014","01","01"]"
)不符合RFC,因此根据浏览器提供不同的结果.
This is due to new Date("2014-01-01")
being created through the Date parse which considers this date to be UTC and then apply the timezone but new Date(["2014","01","01"])
is treated as literal values for each of the parameters in the constructor for your timezone. Although as mentioned in one of the comments below the format new Date(["2014","01","01"])
does not conform to RFC and hence provides different results depending on the browser.
来自: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date
注意:由于浏览器的差异和不一致,强烈建议不要使用Date构造函数(和Date.parse(),以相同的方式工作)来解析日期字符串.仅根据约定,对RFC 2822格式字符串的支持.对ISO 8601格式的支持有所不同,因为仅日期字符串(例如"1970-01-01")被视为UTC,而不是本地.
Note: Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
也许您追求的是 new Date(Date.UTC(2014,01,01));
Perhaps what you are after is new Date(Date.UTC(2014,01,01));
Date.UTC in order to create a consistent date that is not bound to the user's configuration.
这篇关于javascript新Date()构造函数对相同的不同格式字符串的歧义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!