无法在 Firefox 中解析可以在 Chrome 中解析的日期

Cannot parse date in Firefox that can be parsed in Chrome

我有一组日期,例如 June 2017October 2016 等。

在 Firefox 中,执行 new Date('June 2017') 会触发 Invalid Date 错误。在 Chrome.

中同样有效

我尝试使用 Moment.js 但结果是一样的。

如何让它正常工作?

这里有一个 Pen 可以快速测试,与代码片段相同(检查您的浏览器控制台):

var date = 'June 2017';
var formatDate = new Date(date);

console.log(formatDate);

浏览器之间确实存在差异。根据 MDN:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) 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.

如果你的字符串总是Month Year的形式,你可以考虑如下解析。

function parseDateString(str) {
  let months = ['January', 'February', 'March',
        'April', 'May', 'June', 'July', 'August',
        'September', 'October', 'November', 'December'];
  let split = str.split(/\s+/);
  return new Date(Date.UTC(parseInt(split[1], 10), months.indexOf(split[0])));
}

function test(str) {
  console.log(`"${str}" is parsed as`, parseDateString(str));
}

test('June 2017');
test('October 2016');
test('March 2018');