Reputation: 4544
Referring to the documentation of moment.js String + Formats I expected these two lines to return the same date object:
moment('12.05.1989', ['DD.MM.YYYY','YYYY-MM-DD']);
moment('1989-05-12', ['DD.MM.YYYY','YYYY-MM-DD']);
However, what I get is this for the first date:
{ _i: '12.05.1989',
_f: 'YYYY-MM-DD',
_l: undefined,
_isUTC: false,
_a:
[ 12,
4,
19,
0,
0,
0,
0 ],
_d: Sat May 19 12 00:00:00 GMT+0200 (W. Europe Summer Time),
_isValid: true }
While the second is correct:
{ _i: '1989-05-12',
_f: 'YYYY-MM-DD',
_l: undefined,
_isUTC: false,
_a:
[ 1989,
4,
12,
0,
0,
0,
0 ],
_d: Fri May 12 1989 00:00:00 GMT+0200 (W. Europe Summer Time),
_isValid: true }
When I change the order of the formats in the array, it is exactly the other way around, it uses the last format in array.
What am I doing wrong?
I want to avoid workarounds like checking the string for "-" or ".".
Upvotes: 0
Views: 2124
Reputation: 203359
The documentation states:
The parser ignores non-alphanumeric characters, so both of the following will return the same thing.
moment("12-25-1995", "MM-DD-YYYY");
moment("12\25\1995", "MM-DD-YYYY");
In your case, it will match 12.05.1989
against your last pattern (YYYY-MM-DD
) and parse it as "day 1989 of the 5th month of the year 12" (and truncates the day because it otherwise doesn't make sense).
I'm not sure how to prevent this from happening, though, so it might require you to normalize your date formats:
> '12.05.1989'.replace(/(\d{2})\.(\d{2})\.(\d{4})/, '$3-$2-$1')
'1989-05-12'
Upvotes: 2