什么是 JavaScript 中的有效日期时间字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51715259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are valid Date Time Strings in JavaScript?
提问by str
When using new Dateor Date.parsein JavaScript, I cannot just pass arbitrary date formats. Depending on the format, I get a different date than I wanted to or even Invalid Dateinstead of a date object. Some date formats work in one browser but not in others. So which date time formats should I use?
在使用new Date或Date.parse在 JavaScript 中时,我不能只传递任意日期格式。根据格式,我得到的日期与我想要的不同,甚至Invalid Date不是日期对象。某些日期格式在一种浏览器中有效,但在其他浏览器中无效。那么我应该使用哪种日期时间格式?
Additional questions:
补充问题:
Do all browsers support the same formats? How do Mozilla Firefox, Google Chrome, Microsoft Internet Explorer, Microsoft Edge, and Apple Safari handle date time strings? What about Node.js?
Does it take the local date format into consideration? E.g. if I live in Switzerland and the date format is 30.07.2018, can I use
new Date('30.07.2018')?Does it take the local time zone into consideration?
How can I get a date time string from a date object?
How can I detect invalid date time strings?
How do date libraries like Moment.js handle date strings?
所有浏览器都支持相同的格式吗?Mozilla Firefox、Google Chrome、Microsoft Internet Explorer、Microsoft Edge 和 Apple Safari 如何处理日期时间字符串?Node.js 呢?
它是否考虑了本地日期格式?例如,如果我住在瑞士并且日期格式是 30.07.2018,我可以使用
new Date('30.07.2018')吗?是否考虑了当地时区?
如何从日期对象中获取日期时间字符串?
如何检测无效的日期时间字符串?
像 Moment.js 这样的日期库如何处理日期字符串?
In case you did not notice, I answered my own question (why?).
如果你没有注意到,我回答了我自己的问题(为什么?)。
回答by str
The Essentials
要点
JavaScript officially supports a simplificationof the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ. The letter Tis the date/time separator and Zis the time zone offset specified as Z(for UTC) or either +or -followed by a time expression HH:mm.
Some parts (e.g. the time) of that format can be omitted.
JavaScript 正式支持ISO 8601 扩展格式的简化。格式如下:YYYY-MM-DDTHH:mm:ss.sssZ. 字母T是日期/时间分隔符,Z是指定为Z(对于 UTC)的时区偏移量,+或-后跟时间表达式HH:mm。该格式的某些部分(例如时间)可以省略。
Note that years musthave at least four digits, month/day/hours/minutes/seconds musthave exactly two digits, and milliseconds musthave exactly three digits. For example, 99-1-1is not a valid date string.
请注意,年份必须至少有四位数字,月/日/小时/分钟/秒必须恰好有两位数字,而毫秒必须恰好有三位数字。例如,99-1-1不是有效的日期字符串。
These are some examples of valid date (time) strings:
这些是有效日期(时间)字符串的一些示例:
2018-12-302018-12-30T20:592018-12-30T20:59:002018-12-30T20:59:00.000Z2018-12-30T20:59:00.000+01:002018-12-30T20:59:00.000-01:00
2018-12-302018-12-30T20:592018-12-30T20:59:002018-12-30T20:59:00.000Z2018-12-30T20:59:00.000+01:002018-12-30T20:59:00.000-01:00
When you omit the time zone offset, date-times are interpreted as user local time. When you omit the time altogether, dates are interpreted as UTC.
当您省略时区偏移时,日期时间被解释为用户本地时间。当您完全省略时间时,日期将被解释为 UTC。
Important:
All modern and reasonably old browsers and implementations support the full-lengthdate time format according to the specification.
However, there are differences in the handling of date (time) strings without a time zone (see "Missing Time Zone Offset" below for details). You should notuse date time strings without a time zone (Status 2018).
Instead pass a unix timestamp in milliseconds or separate arguments for different parts of the dateto the Dateconstructor.
重要提示:根据规范,所有现代和相当老的浏览器和实现都支持全长日期时间格式。
但是,没有时区的日期(时间)字符串的处理存在差异(有关详细信息,请参阅下面的“缺少时区偏移量”)。你应该不是没有时区(状态2018)使用日期时间字符串。而是将一个以毫秒为单位的Unix 时间戳或日期不同部分的单独参数传递给Date构造函数。
Most browser also support some other formats but they are not specified and thus don't work in all browsers the same way. If at all, you should only use the date time string formats explained above. Every other format might break in other browsers or even in other versions of the same browser.
大多数浏览器还支持一些其他格式,但没有指定它们,因此在所有浏览器中的工作方式不同。如果有的话,您应该只使用上面解释的日期时间字符串格式。其他所有格式都可能在其他浏览器甚至同一浏览器的其他版本中崩溃。
If you run into Invalid Dateinstead of a date object, you most probably are using an invalid date time string.
如果您遇到Invalid Date而不是日期对象,您很可能正在使用无效的日期时间字符串。
And now with a little more detail.
现在有更多的细节。
Date Time String Format
日期时间字符串格式
ECMAScript (the specification that the JavaScript language implements) has been supporting date strings in new Date(specification) and Date.parse(specification) since its inception.
However, the first versions did not actually specify a date time format.
This changed in 2009 when ES5 was introduced with a specification of a date time format.
ECMAScript(JavaScript 语言实现的规范)从一开始就支持new Date(规范)和Date.parse(规范)中的日期字符串。但是,第一个版本实际上并没有指定日期时间格式。这在 2009 年发生了变化,当时 ES5 引入了日期时间格式的规范。
The Basics
基础
ECMAScript specifies the Date Time String Formatas a simplificationof the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ.
ECMAScript中指定的日期时间字符串格式为简化了的ISO 8601扩展格式。格式如下:YYYY-MM-DDTHH:mm:ss.sssZ.
YYYYis the decimal digits of the year 0000 to 9999 in the proleptic Gregorian calendar.-(hyphen) appears literally twice in the string.MMis the month of the year from 01 (January) to 12 (December).DDis the day of the month from 01 to 31.Tappears literally in the string, to indicate the beginning of the time element.HHis the number of complete hours that have passed since midnight as two decimal digits from 00 to 24.:(colon) appears literally twice in the string.mmis the number of complete minutes since the start of the hour as two decimal digits from 00 to 59.ssis the number of complete seconds since the start of the minute as two decimal digits from 00 to 59..(dot) appears literally in the string.sssis the number of complete milliseconds since the start of the second as three decimal digits.Zis the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expressionHH:mm
YYYY是公历中 0000 到 9999 年的十进制数字。-(连字符)在字符串中出现两次。MM是一年中从 01(一月)到 12(十二月)的月份。DD是从 01 到 31 的月份中的第几天。T字面出现在字符串中,以指示时间元素的开始。HH是自午夜以来经过的完整小时数,以两位十进制数字表示,从 00 到 24。:(冒号) 在字符串中出现两次。mm是从一小时开始的完整分钟数,以 00 到 59 的两位十进制数字表示。ss是从 00 到 59 的两位十进制数字表示自分钟开始以来的完整秒数。.(点)字面出现在字符串中。sss是从秒开始的完整毫秒数,以三位十进制数字表示。Z是指定为“Z”(对于 UTC)或“+”或“-”后跟时间表达式的时区偏移量HH:mm
The specification also mentionsthat if "the String does not conform to [the specified] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats" which might result in different dates in different browsers.
该规范还提到,如果“字符串不符合 [指定的] 格式,该函数可能会回退到任何特定于实现的启发式或特定于实现的日期格式”,这可能会导致不同浏览器中的日期不同。
ECMAScript does not take any user local date time formats into account which means that you can not use country or region-specific date time formats.
ECMAScript 不考虑任何用户本地日期时间格式,这意味着您不能使用特定于国家或地区的日期时间格式。
Short Date (and Time) Forms
短日期(和时间)表格
The specification also includes shorter formats as follows.
该规范还包括以下更短的格式。
This format includes date-only forms:
YYYYYYYY-MMYYYY-MM-DDIt also includes “date-time” forms that consist of one of the above date-only forms immediately followed by one of the following time forms with an optional time zone offset appended:
THH:mmTHH:mm:ssTHH:mm:ss.sss
此格式包括仅日期格式:
YYYYYYYY-MMYYYY-MM-DD它还包括“日期-时间”形式,其中包含上述仅日期形式之一,紧接着是以下时间形式之一,并附加可选的时区偏移量:
THH:mmTHH:mm:ssTHH:mm:ss.sss
Fallback Values
回退值
[...] If the
MMorDDfields are absent"01"is used as the value. If theHH,mm, orssfields are absent"00"is used as the value and the value of an absentsssfield is"000". When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
[...] 如果
MM或DD字段不存在,"01"则用作值。如果HH、mm、 或ss字段不存在"00"则用作值,而不存在sss字段的值为"000"。当不存在时区偏移时,仅日期形式被解释为 UTC 时间,日期时间形式被解释为本地时间。
See "Missing Time Zone Offset" below for more information on the lacking browser support.
有关缺少浏览器支持的更多信息,请参阅下面的“缺少时区偏移”。
Out of Bound Values
越界值
Illegal values (out-of-bounds as well as syntax errors) in a format string means that the format string is not a valid instance of this format.
格式字符串中的非法值(越界以及语法错误)意味着该格式字符串不是该格式的有效实例。
For example, new Date('2018-01-32')and new Date('2018-02-29')will result in a Invalid Date.
例如,new Date('2018-01-32')andnew Date('2018-02-29')将导致 Invalid Date.
Extended Years
延长年限
The date time format of ECMAScript also specifies extended yearswhich are six digit year values.
An example of such an extended year string format looks like +287396-10-12T08:59:00.992Zwhich denotes a date in the year?287396 A.D.
Extended years can either be positive or negative.
ECMAScript 的日期时间格式还指定了扩展年份,即六位数年份值。此类扩展年份字符串格式的示例如下所示+287396-10-12T08:59:00.992Z,表示年份中的日期?287396 AD 扩展年份可以是正数也可以是负数。
Date API
日期API
ECMAScript specifies a wide range of date object properties.
Given a valid date object, you can use Date.prototype.toISOString()to get a valid date time string.
Note that the time zone is always UTC.
ECMAScript 指定了广泛的日期对象属性。给定一个有效的日期对象,您可以使用它Date.prototype.toISOString()来获取有效的日期时间字符串。请注意,时区始终为 UTC。
new Date().toISOString() // "2018-08-05T20:19:50.905Z"
It is also possible to detect whether a date object valid or an Invalid Dateusing the following function.
还可以Invalid Date使用以下函数检测日期对象是否有效或是否有效。
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
Source and more information can be found in Detecting an “invalid date” Date instance in JavaScript.
可以在检测 JavaScript 中的“无效日期”日期实例中找到源代码和更多信息。
Examples
例子
Valid Date Time Formats
有效的日期时间格式
The following date time formats are all valid according to the specification and should work in every browser, Node.js or other implementation that supports ES2016 or higher.
根据规范,以下日期时间格式都是有效的,并且应该适用于所有支持 ES2016 或更高版本的浏览器、Node.js 或其他实现。
2018
2018-01
2018-01-01
2018-01-01T00:00
2018-01-01T00:00:00
2018-01-01T00:00:00.000
2018-01-01T00:00:00.000Z
2018-01-01T00:00:00.000+01:00
2018-01-01T00:00:00.000-01:00
+002018-01-01T00:00:00.000+01:00
Invalid Date Time Formats
无效的日期时间格式
Note that the following examples are invalid as per the specification. However, that does not mean that no browser or other implementation interprets them to a date. Please do not use any of the date time formats belowas they are non-standard and might fail in some browsers or browser versions.
请注意,根据规范,以下示例无效。但是,这并不意味着没有浏览器或其他实现将它们解释为日期。请不要使用以下任何日期时间格式,因为它们是非标准的,并且在某些浏览器或浏览器版本中可能会失败。
2018-1-1 // month and date must be two digits
2018-01-01T0:0:0.0 // hour/minute/second must be two digits, millisecond must be three digits
2018-01-01 00:00 // whitespace must be "T" instead
2018-01-01T00 // shortest time part must have format HH:mm
2018-01-01T00:00:00.000+01 // time zone must have format HH:mm
Browser Support
浏览器支持
Today, every modern and reasonably old browser supports the date time formatthat was introduced with the ES5 specification in 2009.
However, even today (Status 2018) there are different implementations for date time strings without a time zone (see "Missing Time Zone Offset" below).
If you need to support older browsers or use strings without a time zone, you should not use date time strings.
Instead, pass a number of milliseconds since January 1, 1970, 00:00:00 UTCor two or more arguments representing the different date partsto the Dateconstructor.
今天,每个现代且相当老的浏览器都支持2009 年 ES5 规范引入的日期时间格式。然而,即使在今天(Status 2018),对于没有时区的日期时间字符串也有不同的实现(参见“Missing Time Zone Offset “ 以下)。
如果您需要支持旧浏览器或使用没有时区的字符串,则不应使用日期时间字符串。相反,将自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数或两个或多个表示不同日期部分的参数传递给Date构造函数。
Missing Time Zone Offset
缺少时区偏移
ES5.1 incorrectlystates that the value of an absent time zone offset is “Z”which contradicts with ISO 8601.
This mistake was fixed in ES6 (ES2015)and extended on in ES2016(see "Changes to the ECMAScript Specifications" below).
As of ES2016, date time strings without a time zone are parsed as local time while date only strings are parsed as UTC.
ES5.1错误地指出不存在时区偏移的值“Z”与 ISO 8601 相矛盾。这个错误在ES6 (ES2015) 中被修复并在ES2016 中扩展(参见下面的“对 ECMAScript 规范的更改”)。从 ES2016 开始,没有时区的日期时间字符串被解析为本地时间,而只有日期的字符串被解析为 UTC。
According to this answer, some implementations never implemented the behaviour specified in ES5.1.
One of them seems to be Mozilla Firefox.
Other browsers that seem to be compliant with the specification of ES2016 (and higher) are Google Chrome 65+, Microsoft Internet Explorer 11, and Microsoft Edge.
The current version of Apple Safari (11.1.2) is notcompliant as it erroneously parses date time strings without a time zone (e.g. 2018-01-01T00:00) as UTC instead of local time.
根据这个答案,一些实现从未实现 ES5.1 中指定的行为。其中之一似乎是 Mozilla Firefox。其他似乎符合 ES2016(及更高版本)规范的浏览器包括 Google Chrome 65+、Microsoft Internet Explorer 11 和 Microsoft Edge。当前版本的 Apple Safari (11.1.2)不兼容,因为它错误地将没有时区的日期时间字符串(例如2018-01-01T00:00)解析为 UTC 而不是本地时间。
Legacy Date Time Formats
传统日期时间格式
ES5 introduced a specification for date time strings in 2009. Before that, there were no specified formats that were supported by all browsers. As a result, each browser vendor added support for different formats which often did not work accross different browsers (and versions). For a small example of ancient history, see date-formats.
ES5 在 2009 年引入了日期时间字符串的规范。在此之前,没有所有浏览器都支持的指定格式。因此,每个浏览器供应商都增加了对不同格式的支持,这些格式通常不适用于不同的浏览器(和版本)。有关古代历史的一个小例子,请参阅日期格式。
Most browsers still support those legacy formats in order to not break the backward compatibility of older websites. But it is not safe to rely on those non-standard formats as they might be inconsistent or get removed at any time.
大多数浏览器仍然支持这些旧格式,以免破坏旧网站的向后兼容性。但是依赖那些非标准格式是不安全的,因为它们可能会不一致或随时被删除。
Date.prototype.toString()and Date.prototype.toUTCString()
Date.prototype.toString()和 Date.prototype.toUTCString()
ES2018 for the first time specified the date format that is returned by Date.prototype.toString()and Date.prototype.toUTCString().
Already before that, the ECMA Specification required the Dateconstructor and Date.parseto correctly parse the formats returned by those methods (even though it did not specify a format before 2018).
ES2018 首次指定了Date.prototype.toString()和返回的日期格式Date.prototype.toUTCString()。在此之前,ECMA 规范需要Date构造函数并Date.parse正确解析这些方法返回的格式(即使它在 2018 年之前没有指定格式)。
An example return value of Date.prototype.toString()may look like this:
的示例返回值Date.prototype.toString()可能如下所示:
Sun Feb 03 2019 14:27:49 GMT+0100 (Central European Standard Time)
Note that the timezone name within brackets is optional and the exact name is "implementation-dependent".
请注意,括号内的时区名称是可选的,确切的名称是“依赖于实现的”。
Date.prototype.toUTCString()returns a date in a similar format as Date.prototype.toString()but with a zero timezone offset. An example format may look like this:
Date.prototype.toUTCString()以类似的格式返回一个日期,Date.prototype.toString()但时区偏移为零。示例格式可能如下所示:
Sun, 03 Feb 2019 13:27:49 GMT
Note that there is a comma ,after the weekday and day month are reversed compared to Date.prototype.toUTCString().
请注意,,与Date.prototype.toUTCString().
As those formats have only been specified in 2018, you should not rely on them working equally in different implementations (especially older browsers).
由于这些格式仅在 2018 年才被指定,因此您不应依赖它们在不同的实现(尤其是旧浏览器)中同等工作。
Node.js
节点.js
Node.js is running on the V8 JavaScript engine which is also used in Google Chrome. So the same specification regarding the date time string format applies.As the code runs in the backend though, the user local time does not influence the time zones but only the settings on the server do. Most platform as a service (PaaS) provider that host Node.js applications use UTC as their default time zone.
Node.js 在 V8 JavaScript 引擎上运行,该引擎也在 Google Chrome 中使用。因此,适用于日期时间字符串格式的相同规范。由于代码在后端运行,因此用户本地时间不会影响时区,而只会影响服务器上的设置。大多数托管 Node.js 应用程序的平台即服务 (PaaS) 提供商使用 UTC 作为其默认时区。
Date Time Libraries
日期时间库
Moment.js
时刻.js
Moment.jsis a very popular library to help with the handling of dates in JavaScript and it also supports more formatsthan ECMAScript specifies. In addition, Moment.js also supports creating date objects based on a string and a arbitrary format.
Moment.js是一个非常流行的库,用于帮助处理 JavaScript 中的日期,它还支持比 ECMAScript 指定的更多格式。此外,Moment.js 还支持基于字符串和任意格式创建日期对象。
Luxon
卢克森
Luxonsupports parsingof ISO 8601, HTTP, RFC2822, SQL, and arbitrary formats. But only using different functions for different date time formats.
Luxon支持解析ISO 8601、HTTP、RFC2822、SQL 和任意格式。但仅针对不同的日期时间格式使用不同的函数。
Changes to the ECMAScript Specifications
ECMAScript 规范的变化
A list of notable changes in the ECMAScript specifications regarding date time string formats.
ECMAScript 规范中有关日期时间字符串格式的显着更改列表。
Changes in ES2018
ES2018 的变化
Introduces a specification for the date formats returned by Date.prototype.toString()and Date.prototype.toUTCString().
介绍Date.prototype.toString()和返回的日期格式的规范Date.prototype.toUTCString()。
Changes in ES2017
ES2017 的变化
No notable changes.
无明显变化。
Changes in ES2016
ES2016 的变化
If the time zone offset is absent, the date-time is interpreted as a local time.When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
如果不存在时区偏移量,则日期时间将被解释为本地时间。当不存在时区偏移时,仅日期形式被解释为 UTC 时间,日期时间形式被解释为本地时间。
Changes in ES6 (ES2015)
在变化ES6(ES2015)
The value of an absent time zone offset is“Z”.If the time zone offset is absent, the date-time is interpreted as a local time.
不存在的时区偏移的值为“Z”。如果不存在时区偏移量,则日期时间将被解释为本地时间。
From Corrections and Clarifications in ECMAScript 2015 with Possible Compatibility Impact:
来自ECMAScript 2015 中的更正和澄清,可能对兼容性产生影响:
If a time zone offset is not present, the local time zone is used. Edition 5.1 incorrectly stated that a missing time zone should be interpreted as
"z".
如果不存在时区偏移量,则使用本地时区。5.1 版错误地指出,缺少的时区应解释为
"z".
See Date Time String Format: default time zone difference from ES5 not web-compatiblefor more details on that change.
有关该更改的更多详细信息,请参阅日期时间字符串格式:与 ES5 不兼容的默认时区差异。
Changes in ES5.1
ES5.1 的变化
If the
MMorDDfields are absent“01”is used as the value. If theHH,mm, orssfields are absent“00”is used as the value and the value of an absentsssfield is“000”. The value of an absent time zone offset is“Z”.
如果
MM或DD字段不存在“01”,则将其用作值。如果HH、mm、 或ss字段不存在“00”则用作值,而不存在sss字段的值为“000”。不存在的时区偏移的值为“Z”。
Changes in ES5
ES5 的变化
First introduction of a date time string format to the ECMAScript specification.
ECMAScript 规范中首次引入了日期时间字符串格式。
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows:
YYYY-MM-DDTHH:mm:ss.sssZ
ECMAScript 基于 ISO 8601 扩展格式的简化定义了日期时间的字符串交换格式。格式如下:
YYYY-MM-DDTHH:mm:ss.sssZ
Also introduces Date.prototype.toISOString()which returns a date time string in that specified format.
还介绍Date.prototype.toISOString()which 返回指定格式的日期时间字符串。
Changes in ES3
ES3 的变化
Deprecates Date.prototype.toGMTString()and replaces it with Date.parse(x.toUTCString())in the section mentioning that the format returned by these methods must be correctly parseable by implmentations of Date.parse. Note that the format returned by Date.parse(x.toUTCString())is "implementation-dependent".
弃用Date.prototype.toGMTString(),并替换它Date.parse(x.toUTCString())的部分提的是,这些方法返回的格式必须是由implmentations正确解析的Date.parse。请注意,返回的格式Date.parse(x.toUTCString())是“依赖于实现的”。
Changes in ES2
ES2 的变化
No notable changes.
无明显变化。
Initial Specification: ES1
初始规格:ES1
ES1 introduced date time strings to be used in new Date(value)and Date.parse(value).
However, it did not specify an actual date (time) format, it even states that
ES1 引入了用于new Date(value)和 的日期时间字符串Date.parse(value)。但是,它没有指定实际的日期(时间)格式,它甚至指出
[...] the value produced by
Date.parseis implementation dependent [...]
[...] 产生的价值
Date.parse取决于实现 [...]
The specification also mentions that
该规范还提到
If
xis any Date object [...], then all of the following expressions should produce the same numeric value in that implementation [...]:
- [...]
Date.parse(x.toString())Date.parse(x.toGMTString())
如果
x是任何日期对象 [...],则以下所有表达式都应在该实现 [...] 中产生相同的数值:
- [...]
Date.parse(x.toString())Date.parse(x.toGMTString())
However, the returned value of both Date.prototype.toString()and Date.prototype.toGMTString()were specified as "implementation dependent".
然而,同时返回的值Date.prototype.toString(),并Date.prototype.toGMTString()已指定为“实现相关”。
回答by RobG
So which date time formats should I use?
那么我应该使用哪种日期时间格式?
The general recommendation is to not use the built-in parser at all as it's unreliable, so the answer to "should" is "none". See Why does Date.parse give incorrect results?
一般建议是根本不使用内置解析器,因为它不可靠,因此“应该”的答案是“无”。请参阅为什么 Date.parse 给出不正确的结果?
However, as str says, you can likely use the format specified in ECMA-262 with a timezone: YYYY-MM-DDTHH:mm:ss.sssZor YYYY-MM-DDTHH:mm:ss.sss±HH:mm, don't trust any other format.
但是,正如 str 所说,您可能可以使用 ECMA-262 中指定的格式和时区:YYYY-MM-DDTHH:mm:ss.sssZ或者YYYY-MM-DDTHH:mm:ss.sss±HH:mm,不要相信任何其他格式。
Do all browser support the same formats?
所有浏览器都支持相同的格式吗?
No.
不。
How do Mozilla Firefox, Google Chrome, Microsoft Internet Explorer, Microsoft Edge, and Apple Safari handle date time strings?
Mozilla Firefox、Google Chrome、Microsoft Internet Explorer、Microsoft Edge 和 Apple Safari 如何处理日期时间字符串?
Differently. Anything other than the format in ECMA-262 is implementation dependent, and there are bugs in parsing the the ECMA-262 format.
不同。ECMA-262 格式以外的任何内容都依赖于实现,并且在解析 ECMA-262 格式时存在错误。
What about Node.js?
Node.js 呢?
Likely different again, see above.
可能再次不同,见上文。
Does it take the local date format into consideration? E.g. if I live in Switzerland and the date format is 30.07.2018, can I use new Date('30.07.2018')?
它是否考虑了本地日期格式?例如,如果我住在瑞士并且日期格式是 30.07.2018,我可以使用 new Date('30.07.2018') 吗?
Maybe. Since it's not the standard format, parsing is implementation dependent, so maybe, maybe not.
或许。由于它不是标准格式,解析依赖于实现,所以也许,也许不是。
Does it take the local time zone into consideration?
是否考虑了当地时区?
It uses the host timezone offset where the string is parsed as local and to generate the string displayed using local times. Otherwise it uses UTC (and the internal time value is UTC).
它使用主机时区偏移量,其中字符串被解析为本地并生成使用本地时间显示的字符串。否则,它使用 UTC(内部时间值为 UTC)。
How can I get a date time string from a date object?
如何从日期对象中获取日期时间字符串?
Date.parse.toString, or see Where can I find documentation on formatting a date in JavaScript?
Date.parse.toString,或参见我在哪里可以找到有关在 JavaScript 中格式化日期的文档?
How can I detect invalid date time strings?
如何检测无效的日期时间字符串?
One of the first 3 answers hereshould answer that.
这里的前 3 个答案之一应该回答这个问题。
How do date libraries like Moment.js handle date strings?
像 Moment.js 这样的日期库如何处理日期字符串?
They parse them based on either a default or provided format. Read the source (e.g. fecha.jsis a simple parser and formatter with well written, easy to follow code).
他们根据默认格式或提供的格式解析它们。阅读源代码(例如fecha.js是一个简单的解析器和格式化程序,代码编写良好,易于遵循)。
A parser isn't hard to write, but trying to guess the input format (as built-in parsers tend to do) is fraught, unreliable and inconsistent across implementations. So the parser should require the format to be provided unless the input string is in the parser's default format.
解析器不难编写,但尝试猜测输入格式(如内置解析器往往会做的那样)是令人担忧的、不可靠的和跨实现的不一致。所以解析器应该要求提供格式,除非输入字符串是解析器的默认格式。
PS
聚苯乙烯
There are changes to the formats of strings that implementations must support for parsing and formatting in ECMAScript 2019 (currently in draft), but I think the general advice to avoid the built–in parser will stand for some time yet.
在 ECMAScript 2019(目前处于草案中)中,实现必须支持解析和格式化的字符串格式发生了变化,但我认为避免内置解析器的一般建议将持续一段时间。

