If I specify YYYY-MM-17
as a date to moment.js, it says it is a valid date:
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/
I'm also seeing different results on different browsers. According to the 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.
This is not what I am seeing. When natively specifying a date using the same format:
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/
Turns out there is a strict option. From the 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With