Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chuyler opened this issue Feb 24, 2023 · 0 comments
Open

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

chuyler opened this issue Feb 24, 2023 · 0 comments

Comments

@chuyler
Copy link

chuyler commented Feb 24, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant