Skip to content

Commit 33a46cc

Browse files
committed
Internationalize date formatting
1 parent 4b7bdd9 commit 33a46cc

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

client/i18n.js

+13
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import i18n from 'i18next';
22
import { initReactI18next } from 'react-i18next';
33
import LanguageDetector from 'i18next-browser-languagedetector';
44
import Backend from 'i18next-http-backend';
5+
import { enUS, es } from 'date-fns/locale';
56

67
const fallbackLng = ['en-US'];
78
const availableLanguages = ['en-US', 'es-419'];
@@ -14,6 +15,18 @@ export function languageKeyToLabel(lang) {
1415
return languageMap[lang];
1516
}
1617

18+
export function languageKeyToDateLocale(lang) {
19+
const languageMap = {
20+
'en-US': enUS,
21+
'es-419': es
22+
};
23+
return languageMap[lang];
24+
}
25+
26+
export function currentDateLocale() {
27+
return languageKeyToDateLocale(i18n.language);
28+
}
29+
1730
const options = {
1831
loadPath: '/locales/{{lng}}/translations.json',
1932
requestOptions: { // used for fetch, can also be a function (payload) => ({ method: 'GET' })

client/utils/formatDate.js

+5-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import isValid from 'date-fns/isValid';
55
import parseISO from 'date-fns/parseISO';
66
import i18next from 'i18next';
77

8+
import { currentDateLocale } from '../i18n';
9+
810
function parse(maybeDate) {
911
const date = maybeDate instanceof Date ? maybeDate : parseISO(maybeDate);
1012

@@ -34,7 +36,8 @@ export default {
3436
}
3537

3638
const timeAgo = formatDistanceToNow(parsed, {
37-
includeSeconds: false
39+
includeSeconds: false,
40+
locale: currentDateLocale()
3841
});
3942
return i18next.t('formatDate.Ago', { timeAgo });
4043
}
@@ -46,7 +49,7 @@ export default {
4649
const formatType = showTime ? 'PPpp' : 'PP';
4750

4851
if (parsed) {
49-
return format(parsed, formatType);
52+
return format(parsed, formatType, { locale: currentDateLocale() });
5053
}
5154

5255
return '';

0 commit comments

Comments
 (0)