Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment JS Parse strange behaviour

I'm using moment.parse String+Format method

when I call moment("=min(C2:C4)", 'DD/MM/YYYY') it evaluates to valid date

Sun Apr 02 2017 00:00:00 GMT+0300 (FLE Daylight Time)

I can't understand how moment parses "=min(C2:C4)" to valid date. Just wonder, some one can explain.

like image 566
Mikhail Avatar asked Feb 02 '26 01:02

Mikhail


1 Answers

From Moment.js docs:

Moment's parser is very forgiving, and this can lead to undesired/unexpected behavior.

Short answer: because of your expected loose format, moment parses the 2 as the day and the 4 as the month.

Long answer:

Visualizing this might be easier if you run your command in a console and view the results. I'd recommend taking a look there first, and I'll explain the important parts below.

  1. Date string vs. format

You've specified your string as "=min(C2:C4)" and your format as DD/MM/YYYY, so moment is looking for a date in that general format: a day followed by a month followed by a year.

  1. moment._pf.unusedTokens[]

This is an array and has one value, 'YYYY'; the parser did not find a year, but it did find a day and a month... hmmm.

  1. moment._pf.unusedInput[]

This tells us more - an array with three values:

1. '=min(C'
2. ':C'
3. ')'

Looks like moment found the 2 and the 4 to match day and month. You'll find these values in the moment._pf.parsedDateParts array.

So, that should explain why the date is April 2, 2017. The month of 3 (this is the finalized month, not the actual value parsed. Months are zero-indexed, so it's back to "4") and the day of 2. No year was given, so moment assumes it's the current year. No time was given, so it assumes the start of the day.

If you don't want this behavior you should pass a 3rd / last param as true (strict matching). Check http://momentjs.com/docs/#/parsing/string-format/ for more details.

like image 100
chazsolo Avatar answered Feb 03 '26 16:02

chazsolo