you-dont-need / You-Dont-Need-Momentjs

List of functions which you can use to replace moment.js + ESLint Plugin
MIT License
13.27k stars 318 forks source link

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

Open chuyler opened 1 year ago

chuyler commented 1 year ago

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.