Javascript New Date() 返回无效日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46963734/
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
Javascript New Date() returns invalid date
提问by fandul
I have an Array with date strings formatted: "24-Jul-2017".
and when i use new Date("24-Jul-2017");it returns date with one day offset.2017-07-23T22:00:00.000Z
我有一个日期字符串格式的数组:“24-Jul-2017”。
当我使用new Date("24-Jul-2017");它时,它会返回带有一天偏移量的日期。2017-07-23T22:00:00.000Z
Tried different formatting but could not get correct date.
尝试了不同的格式,但无法获得正确的日期。
回答by Jon Skeet
Assuming the browser is in a time zone with a UTC offset of +2 at the start of July 24th 2017, it's behaving as documented.
假设浏览器在 2017 年 7 月 24 日开始时处于 UTC 偏移量为 +2 的时区,则其行为如文档所述。
The Dateconstructoris documented as behaving like Date.parse, which then includes this documentation - along with multiple warnings not to use the constructor accepting a string, or the parsemethod:
该Date构造被记录为表现得像Date.parse,然后包括该文档-与多个警告沿不使用构造接受串,或所述parse方法:
Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore Date objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.
给定日期字符串“2014 年 3 月 7 日”,parse() 假定本地时区,但给定 ISO 格式(例如“2014-03-07”),它将假定时区为 UTC(ES5 和 ECMAScript 2015)。因此,除非系统将本地时区设置为 UTC,否则使用这些字符串生成的 Date 对象可能代表不同的时刻,具体取决于支持的 ECMAScript 版本。这意味着看起来等效的两个日期字符串可能会产生两个不同的值,具体取决于正在转换的字符串的格式。
So it's providing you July 24th 2017 at midnight in the local time zone.
因此,它为您提供了当地时间2017 年 7 月 24 日午夜的时间。
It sounds to me like you'd be better off using Moment.jsor something similar to give you clearer control over the parsing/formatting.
在我看来,您最好使用Moment.js或类似的东西来让您更清楚地控制解析/格式。
回答by Punith R Kashi
new Date(Date.UTC(year, month, day, hour, minute, second))
Try this format (UTC will be the timezone for your Date)
尝试这种格式(UTC 将是您日期的时区)

