Skip to content

How do I parse certain locale dates without MomentJS? #139

Open
@chuyler

Description

@chuyler

The example I have would be an input box where the user is allowed to type in a date with their preferred locale format or modify the date shown to them. I am showing German locale because it usually causes typical Date.parse() functions to fail because it doesn't know the month and day are swapped.

function deriveDateFormat(locale) {
  const isoString1 = '1979-02-03'; // example date!
  const isoString2 = '79-2-3'; // example date!

  const intlString = new Date(isoString1).toLocaleDateString(locale, { timeZone: 'UTC' }); // generate a formatted date
  const dateParts1 = isoString1.split('-'); // prepare to replace with pattern parts
  const dateParts2 = isoString2.split('-'); // prepare to replace with pattern parts

  return intlString
    .replace(dateParts1[2], 'DD')
    .replace(dateParts1[1], 'MM')
    .replace(dateParts1[0], 'YYYY')
    .replace(dateParts2[2], 'D')
    .replace(dateParts2[1], 'M')
    .replace(dateParts2[0], 'YY');
}

const myLocale = 'de-DE';
let d = new Date('2023-01-30T05:00:00.000Z');
let dateFormatted = d.toLocaleDateString(myLocale);
// 30.1.2023

// user changes input field
dateFormatted = '31.1.2023';

let nativeParsed = new Date(dateFormatted).toISOString();
// Invalid Date -- WRONG!

let dateParsed = moment(dateFormatted, deriveDateFormat(myLocale)).toISOString();
// 2023-01-31T05:00:00.000Z -- CORRECT!

I will add that this is just an example. Assume I do not know what the user's locale is until the time of execution. I am aware that I could manually convert this particular locale, but I am looking for a generic solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions