当传递给 "new Date" 时,javascript 中的 yyyy-mm-dd 和 yyyy/mm/dd 的结果不同

different result for yyyy-mm-dd and yyyy/mm/dd in javascript when passed to "new Date"

我在 nodejs repl 下执行下面的语句,我在同一日期得到了两个不同的结果

var dateStr1 = "2015/03/31";
var dateStr2 = "2015-03-31";
var date1 = new Date(dateStr1);//gives Tue Mar 31 2015 00:00:00 GMT+0530 (IST)
var date2 = new Date(dateStr2);//gives Tue Mar 31 2015 05:30:00 GMT+0530 (IST)

在第一个小时,分钟,秒都是零,而在第二个默认小时,分钟被设置为时区小时,分钟即5:30

归结为 Date.parse() 如何处理 ISO-8601 date format

The date time string may be in ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed. The UTC time zone is used to interpret arguments in ISO 8601 format that do not contain time zone information (note that ECMAScript ed 6 draft specifies that date time strings without a time zone are to be treated as local, not UTC)

您的第一个日期格式 2015/03/31assumed 2015 年 3 月 31 日凌晨 12 点 在您当前的时区
您的第二个日期格式 2015-03-31 被视为 ISO-8601,并假定为 2015 年 3 月 31 日凌晨 12 点 UTC 时区

链接文档中的 "Differences in assumed time zone" 标题更加详细:

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. Therefore Date objects produced using those strings will represent different moments in time 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 (this behavior is changed in ECMAScript ed 6 so that both will be treated as local).

根据 ECMAScript 标准,第一个字符串“2015/03/31”是不受支持的格式。每当将不受支持的值传递给构造函数时,其行为取决于实现,即标准没有说明实现必须做什么。某些浏览器,如 Firefox,会尝试猜测格式是什么,显然它会在午夜 local 时间创建一个日期对象。其他浏览器可能 return NaN 或以不同方式解释这些部分。

第二个字符串“2015-03-31”是格式正确的 ISO 8601 日期。对于这些字符串,有明确定义的规则,所有浏览器都会将其解释为那个日期,午夜,UTC。