Skip to content

Instantly share code, notes, and snippets.

@anechunaev
Created August 28, 2018 13:23
Show Gist options
  • Save anechunaev/52d2d509244211631916dadc0c22698c to your computer and use it in GitHub Desktop.
Save anechunaev/52d2d509244211631916dadc0c22698c to your computer and use it in GitHub Desktop.
Super simple function to parse date string (date.toLocaleDateString()). It's not bullet-proof, so for more stable parsing use something like moment.js
/**
* Super simple function to parse date string (date.toLocaleDateString())
* It's not bullet-proof, so for more stable parsing use something like moment.js
*
* This function may return invalid date object if the string was not parsed correctly.
* Check for validity:
*
* isNaN(date.valueOf()) // Invalid date if true
*/
private parseLocaleDateString = (localeDate?: string): Date => {
const date = new Date(localeDate!);
const match = (localeDate || '').match(/^(\d{2,4}).*?(\d{2}).*?(\d{2,4})$/);
// Can't parse date string, use default Date.parse()
// It may return correct Date object for strings like "April 22, 1996"
if (!match) return date;
const parts = [match[1], match[2], match[3]];
const MDYLocaleList = [
"en-US",
"en-MH",
"ms-MY",
"ig-NG",
"en-PH",
"fil-PH",
"ar-SA",
"so-SO",
"en-CA",
"mh",
"ms",
"ig",
"fl",
"ar",
"so",
];
// YMD
if (/^(\d{4}).*?(\d{2}).*?(\d{2})$/.test(localeDate || '')) {
return new Date(parts.join('-'));
}
// DMY or MDY?
if (/^(\d{2}).*?(\d{2}).*?(\d{4})$/.test(localeDate || '')) {
// Check for MDY
if (+parts[1] > 12) {
return new Date(`${parts[2]}-${parts[0]}-${parts[1]}`);
}
// Check for MDY based on locale
if (typeof window !== 'undefined') {
if (typeof window.navigator.language !== 'undefined' && MDYLocaleList.indexOf(window.navigator.language) >= 0) {
return new Date(`${parts[2]}-${parts[0]}-${parts[1]}`);
}
// Hello IE!
if ((window.navigator as any).userLanguage && MDYLocaleList.indexOf((window.navigator as any).userLanguage) >= 0) {
return new Date(`${parts[2]}-${parts[0]}-${parts[1]}`);
}
}
// After strict checks for MDY, probably it's DMY
return new Date(parts.reverse().join('-'));
}
// Cant't parse date, so try to use native parser
return date;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment