Home > database >  moment.js parse date with strict format and locale
moment.js parse date with strict format and locale

Time:02-01

I have a use case where I get dates with different locales and I'am trying to parse them into RFC2822.

The issue is that with some locales moment just does not parse the date correctly. For example "24 janv. 2022" does not work.

The locale for the date is "fr"-French and it should match the "ll" format. However I can't seem to make moment parse that string correctly.

Codepen: https://codesandbox.io/s/sad-swirles-21cf9?file=/src/App.js:53-130 (check the console)

Code:

const testString = "24 janv. 2022";
const DATE_RFC2822 = "HH:mm MMM DD YYYY";

const parseDate = (date) => {
const locales = [
  "en",
  "de",
  "fr",
  "es",
  "pl",
  "nl",
  "it",
  "ar",
  "cs",
  "sk",
  "sv",
  "zh-cn",
  "tr",
  "el",
  "fi",
  "he",
  "hi",
  "hu",
  "ko",
  "he"
];

for (let i = 0; i < locales.length; i  ) {
  let parsedDate = moment(
    date,
    ["D. MMM YYYY", "MMM D, YYYY", "D MMM. YYYY", "D MMMM. YYYY", "ll"],
    locales[i],
    true
  );
  if (parsedDate.isValid()) {
    parsedDate.locale("en");
    return {
      success: true,
      object: parsedDate,
      formatted: parsedDate.format(DATE_RFC2822),
      source: date
    };
  } 
}

return {
  success: false,
  object: "",
  formatted: "",
  source: date
}
};

CodePudding user response:

The issue is that you are not properly importing the localization, have a look at Loading locales in NodeJS section in the docs.

The linked code works if you put:

import moment from "moment/min/moment-with-locales";

instead of

import moment from "moment";
  •  Tags:  
  • Related