From 482d8c3f2ea18950c91dce8823dee6b664cf23cd Mon Sep 17 00:00:00 2001 From: Lim Chee Aun Date: Fri, 23 Aug 2024 18:00:04 +0800 Subject: [PATCH] Better locale matching --- src/components/relative-time.jsx | 3 ++- src/utils/nice-date-time.js | 14 +++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/components/relative-time.jsx b/src/components/relative-time.jsx index 9c62c771..9308c643 100644 --- a/src/components/relative-time.jsx +++ b/src/components/relative-time.jsx @@ -16,7 +16,8 @@ function isValidDate(value) { const resolvedLocale = new Intl.DateTimeFormat().resolvedOptions().locale; 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 { return new Intl.DateTimeFormat(lang, opts); } catch (e) {} diff --git a/src/utils/nice-date-time.js b/src/utils/nice-date-time.js index 29019360..adf81c88 100644 --- a/src/utils/nice-date-time.js +++ b/src/utils/nice-date-time.js @@ -7,10 +7,8 @@ const defaultLocale = new Intl.DateTimeFormat().resolvedOptions().locale; const _DateTimeFormat = (opts) => { const { locale, dateYear, hideTime, formatOpts } = opts || {}; - const loc = - locale && !/pseudo/i.test(locale) - ? localeMatch([locale], [defaultLocale], locale) - : defaultLocale; + const regionlessLocale = locale.replace(/-[a-z]+$/i, ''); + const loc = localeMatch([regionlessLocale], [defaultLocale], locale); const currentYear = new Date().getFullYear(); const options = { // Show year if not current year @@ -24,9 +22,11 @@ const _DateTimeFormat = (opts) => { }; try { return Intl.DateTimeFormat(loc, options); - } catch (e) { - return Intl.DateTimeFormat(undefined, options); - } + } catch (e) {} + try { + return Intl.DateTimeFormat(locale, options); + } catch (e) {} + return Intl.DateTimeFormat(undefined, options); }; const DateTimeFormat = mem(_DateTimeFormat);