javascript - moment.js 在解析格式错误的日期时会做一些奇怪的事情

标签 javascript date momentjs

如果我将 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/

关于javascript - moment.js 在解析格式错误的日期时会做一些奇怪的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32355577/

相关文章:

javascript - Ace Editor 可以支持一个页面多个代码编辑器吗?

javascript - Bootbox meteor 形式: preventing blank submissions

sql - 获取开始日期和结束日期之间的日期

javascript - 如何获取HH :MM:SS difference using milliseconds in javascript?

javascript - 我能确定 array.slice() 总是和 array.slice(0) 一样工作吗?

带有计时器的 javascript if else 语句

c# - 尝试通过从日期中减去日期来获取 int

vb.net - 如何将月数添加到 Date 对象?

javascript - 时刻.js : The result is always "a few seconds ago" in firefox/ie

vuejs2 - vuejs2 项目中 moment.js 的全局语言环境