moment.js 在解析格式错误的日期时做了奇怪的事情

moment.js is doing weird things when parsing a badly formatted date

如果我将 YYYY-MM-17 指定为 moment.js 的日期,它会说这是一个有效日期:

var myMoment = moment('YYYY-MM-17', 'YYYY-MM-DD');

console.log(myMoment.isValid()); // -> true

console.log(myMoment.get('year')); // -> 2017
console.log(myMoment.get('month')); // -> 0
console.log(myMoment.get('day')); // -> 0

https://jsfiddle.net/seu6x3k3/3/

我在不同的浏览器上也看到了不同的结果。根据 docs:

... we first check if the string matches known ISO 8601 formats, then fall back to new Date(string) if a known format is not found.

这不是我看到的。当使用相同格式本机指定日期时:

var date = new Date('YYYY-MM-17'); // -> NaN

console.log(date.getYear()); // -> NaN
console.log(date.getMonth()); // -> NaN
console.log(date.getDay()); // -> NaN

https://jsfiddle.net/3p5x1qn3/

原来有一个严格的选项。来自 docs:

Moment's parser is very forgiving, and this can lead to undesired behavior. As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly.

var myMoment = moment('YYYY-MM-17', 'YYYY-MM-DD', true);

console.log(myMoment.isValid()); // -> false

console.log(myMoment.get('year')); // -> 2016
console.log(myMoment.get('month')); // -> 4
console.log(myMoment.get('day')); // -> 0

https://jsfiddle.net/seu6x3k3/5/