javascript中的Date()如何工作? [英] How does the Date() in javascript work?
问题描述
我正在尝试使用JS中的Date函数将"NINE/MAR/2008"解析为:
I am trying to parse "NINE/MAR/2008" using Date function in JS as:
new Date("NINE/MAR/2008")
这给我的结果是:
2008年3月1日星期六
Sat Mar 01 2008
JS中的日期解析会考虑什么逻辑?
What logic does the date parsing in JS consider?
推荐答案
Date
构造函数和 Date.parse
的 only 格式规范要求支持的是:
The only formats that the Date
constructor and Date.parse
are required by the specification to support are:
-
ECMAScript第5版引入的一个 ,例如
2015-04-29
,它是 ISO-8601 ,但它们混淆了时区( ECMAScript 2016 )和
The one introduced by ECMAScript 5th edition in 2009 such as
2015-04-29
, which was meant to be a simplified version of ISO-8601 but they messed up on timezones (fixed in ECMAScript 2015, but then had to be amended again in ECMAScript 2016), and
该JavaScript引擎(未指定)上任何 Date#toString
输出的内容.
Whatever Date#toString
outputs on that JavaScript engine (which is not specified).
大多数JavaScript引擎也将解析 mm/dd/yyyy
(其中所有数字始终以美国格式,月初),但这不是 >指定的行为.有些人可能会解析 yyyy/mm/dd
(请注意/
而不是-
),但这仍然是未定义的行为,尤其是某些引擎可能将其解释为UTC,将其他时间解释为当地时间(这很重要,即使它只是一个没有时间的日期).
Most JavaScript engines will also parse mm/dd/yyyy
(where those are all numbers — always in U.S. format, month-first), but that is not specified behavior. Some may parse yyyy/mm/dd
(note the /
rather than -
), but again it's undefined behavior, and in particular some engines may interpret it as UTC and others as local time (and it matters, even if it's just a date without a time on it).
所有其他日期解析必须由您自己的代码或您使用的库中的代码(例如MomentJS)完成.您可以使用
All other date parsing has to be done by your own code or code in a library that you use, such as MomentJS. You can build a Date
from its constituent parts using the long form of the constructor, e.g.: new Date(2008, 2, 9)
for 9th March, 2008 (note that months start with 0 = January).
这篇关于javascript中的Date()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!