如果我将 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
最佳答案
原来有一个严格的选项。来自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
关于javascript - moment.js 在解析格式错误的日期时会做一些奇怪的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32355577/