Getting a wrong value while converting date from german locale to english using moment

38 Views Asked by At

All I want is to get the date value received in german language to english format for which i tried using moment library as given below

It does convert but unfortunately returns a wrong value.

moment('Mär 29, 2024', 'MMM DD, YYYY', 'de-DE').locale('en-US').format('MM/DD/YYYY')

// Expected Value - 03/29/2024
// received value - 01/29/2024

Is there a fix for this ?

1

There are 1 best solutions below

2
Christopher On

You can simply replace the month names by using the Intl API.

That small function should support nearly all dates formated like this.

function convertLocalizedDateStringToDateObject(strToParse, from) {
  for (let i = 0; i < 12; i++) {
    const date = new Date(new Date().getFullYear(), i, 1);
    const short = date.toLocaleDateString(from, { month: "short" });
    const long = date.toLocaleDateString(from, { month: "long" });
    const shortReplace = date.toLocaleDateString("en-US", { month: "short" });
    const longReplace = date.toLocaleDateString("en-US", { month: "long" });
    const shortMonth = strToParse.replace(short, shortReplace);
    const longMonth = strToParse.replace(long, longReplace);
    if (!isNaN(new Date(shortMonth).valueOf())) {
      return new Date(shortMonth);
    } else if (!isNaN(new Date(longMonth).valueOf())) {
      return new Date(longMonth);
    }
  }
  return new Date(strToParse);
}
// March in Germany is März
console.log(convertLocalizedDateStringToDateObject("Mär 29, 2024", "de-DE"));
console.log(convertLocalizedDateStringToDateObject("24. Dezember 2024", "de-DE"));
// January in Austria is Jänner
console.log(convertLocalizedDateStringToDateObject("Jän 2, 2024", "de-AT"));
console.log(convertLocalizedDateStringToDateObject("7. Jänner 2024", "de-AT"));