I need to parse a date in the “it” locale with momentjs, and I’m doing this
JavaScript
x
8
1
import moment from 'moment';
2
import 'moment/locale/it';
3
4
moment.locale("it");
5
let d = "20/12/2018"; // 20 dec 2018
6
let mm = moment(d);
7
console.log(mm.format("DD MM YYYY"));
8
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
Advertisement
Answer
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
JavaScript
1
7
1
let localeFormat = moment.localeData('it').longDateFormat('L');
2
console.log(localeFormat) // DD/MM/YYYY
3
4
let d = "20/12/2018"; // 20 dec 2018
5
let mm = moment(d, localeFormat);
6
console.log(mm.format("DD MM YYYY"));
7