Moment.js does weird things when parsing a badly formatted date

If I specify YYYY-MM-17 as the date at the time of .js, it says that 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 also see different results in different browsers. According to the docs :

... first, check if the string matches the known ISO 8601 formats, and then returns to new Date(string) if an unknown format is not found.

This is not what I see. When initially indicate the 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/

+7
javascript date momentjs
source share
1 answer

It turns out there is a strict option. From docs :

Moment parser is very forgiving, and this can lead to unwanted behavior. Starting with version 2.3.0, you can specify a boolean for the last argument to force Moment to use strict parsing. Strict analysis 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/

+1
source share

All Articles