Invalid date when parsing with locale it

Tags: , ,

I need to parse a date in the “it” locale with momentjs, and I’m doing this

import moment from 'moment';
import 'moment/locale/it';

let d = "20/12/2018"; // 20 dec 2018
let mm = moment(d);
console.log(mm.format("DD MM YYYY"));

What I get is “invalid date” and I don’t understand why. Can you help me?

Using the “en” locale (with the date written as 12/20/2018) all is ok


The below snippet will accomplish what you want. It takes moment’s date format for a given local and passes it to the constructor when creating a moment.

With that said, the comments above raise a lot of good points and this is not a reliable way to be handling dates.

For example, if someone in Italy entered a date string in the en MM/DD/YYYY format this would break

let localeFormat = moment.localeData('it').longDateFormat('L');
console.log(localeFormat) // DD/MM/YYYY

let d = "20/12/2018"; // 20 dec 2018
let mm = moment(d, localeFormat);
console.log(mm.format("DD MM YYYY"));

Source: stackoverflow