Better locale matching

This commit is contained in:
Lim Chee Aun 2024-08-23 18:00:04 +08:00
parent e5f674cf38
commit 482d8c3f2e
2 changed files with 9 additions and 8 deletions

View file

@ -16,7 +16,8 @@ function isValidDate(value) {
const resolvedLocale = new Intl.DateTimeFormat().resolvedOptions().locale; const resolvedLocale = new Intl.DateTimeFormat().resolvedOptions().locale;
const DTF = mem((locale, opts = {}) => { const DTF = mem((locale, opts = {}) => {
const lang = localeMatch([locale], [resolvedLocale], locale); const regionlessLocale = locale.replace(/-[a-z]+$/i, '');
const lang = localeMatch([regionlessLocale], [resolvedLocale], locale);
try { try {
return new Intl.DateTimeFormat(lang, opts); return new Intl.DateTimeFormat(lang, opts);
} catch (e) {} } catch (e) {}

View file

@ -7,10 +7,8 @@ const defaultLocale = new Intl.DateTimeFormat().resolvedOptions().locale;
const _DateTimeFormat = (opts) => { const _DateTimeFormat = (opts) => {
const { locale, dateYear, hideTime, formatOpts } = opts || {}; const { locale, dateYear, hideTime, formatOpts } = opts || {};
const loc = const regionlessLocale = locale.replace(/-[a-z]+$/i, '');
locale && !/pseudo/i.test(locale) const loc = localeMatch([regionlessLocale], [defaultLocale], locale);
? localeMatch([locale], [defaultLocale], locale)
: defaultLocale;
const currentYear = new Date().getFullYear(); const currentYear = new Date().getFullYear();
const options = { const options = {
// Show year if not current year // Show year if not current year
@ -24,9 +22,11 @@ const _DateTimeFormat = (opts) => {
}; };
try { try {
return Intl.DateTimeFormat(loc, options); return Intl.DateTimeFormat(loc, options);
} catch (e) { } catch (e) {}
try {
return Intl.DateTimeFormat(locale, options);
} catch (e) {}
return Intl.DateTimeFormat(undefined, options); return Intl.DateTimeFormat(undefined, options);
}
}; };
const DateTimeFormat = mem(_DateTimeFormat); const DateTimeFormat = mem(_DateTimeFormat);