Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 326
sennett Avatar asked Sep 02 '15 14:09

sennett


1 Answers

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/

like image 127
sennett Avatar answered Oct 06 '22 12:10

sennett