You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
The text was updated successfully, but these errors were encountered:
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.
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.
The text was updated successfully, but these errors were encountered: