Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions apps/web/src/common/utils/time.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,21 @@ describe('time', () => {
expect(formatToNowStrict('2022-09-28T02:11:54Z')).toBe('2 months');
});
});

describe('time locale', () => {
it('follows the locale that is active at call time', () => {
let locale = 'en';
jest.isolateModules(() => {
jest.doMock('@common/utils/getLocale', () => ({
__esModule: true,
default: () => locale,
}));
const mod = require('./time');
const en = mod.formatToNow('2022-09-28T02:11:54Z');
locale = 'zh';
const zh = mod.formatToNow('2022-09-28T02:11:54Z');
expect(en).toContain('about');
expect(zh).not.toEqual(en);
});
});
});
8 changes: 5 additions & 3 deletions apps/web/src/common/utils/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import { enGB, zhCN } from 'date-fns/locale';
import getLocale from '@common/utils/getLocale';

const FORMAT_YMD = 'yyyy-MM-dd';
const local = getLocale();
const languages = { en: enGB, zh: zhCN };
// Read the locale at call time: capturing it in a module-level constant froze the
// date language for the lifetime of the bundle.
const currentLocale = () => languages[getLocale()];

export const formatISO = (s: string, layout?: string) => {
if (!s) return '';
Expand All @@ -20,13 +22,13 @@ export const formatISO = (s: string, layout?: string) => {
export const formatToNow = (s: string) => {
if (!s) return '';
const p = parseJSON(s);
return formatDistanceToNow(p, { locale: languages[local] });
return formatDistanceToNow(p, { locale: currentLocale() });
};

export const formatToNowStrict = (s: string) => {
if (!s) return '';
const p = parseJSON(s);
return formatDistanceToNowStrict(p, { locale: languages[local] });
return formatDistanceToNowStrict(p, { locale: currentLocale() });
};

export const isTimestampWithinSec = (ts: string, sec: number): boolean => {
Expand Down