From b8d0969c6110ffd8ea13c2e4ab70db3189c6240b Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Wed, 8 Sep 2021 14:55:20 +0800 Subject: [PATCH] feat: add dayjs i18n --- shared/i18n/index.ts | 14 +++++++++++++- shared/utils/date-helper.ts | 11 ++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/shared/i18n/index.ts b/shared/i18n/index.ts index 2ddf6934..6ed489ca 100644 --- a/shared/i18n/index.ts +++ b/shared/i18n/index.ts @@ -8,6 +8,11 @@ import { languageDetector } from './language'; import { useState, useEffect } from 'react'; import HttpApi from 'i18next-http-backend'; // https://github.com/i18next/i18next-http-backend +/** + * 允许出现的语言 + */ +type AllowedLanguage = 'zh-CN' | 'en-US'; + i18next .use(languageDetector) .use(HttpApi) @@ -56,7 +61,7 @@ export const t: TFunction = ( /** * 设置i18next的语言 */ -export async function setLanguage(lang: string): Promise { +export async function setLanguage(lang: AllowedLanguage): Promise { return new Promise((resolve, reject) => { i18next.changeLanguage(lang, (err) => { if (err) { @@ -68,6 +73,13 @@ export async function setLanguage(lang: string): Promise { }); } +/** + * 监听语言变更 + */ +export function onLanguageChange(cb: (lang: string) => void) { + i18next.on('languageChanged', cb); +} + /** * fork from i18next/react-i18next/-/blob/src/useTranslation.js * i18n for react 使用hooks diff --git a/shared/utils/date-helper.ts b/shared/utils/date-helper.ts index 0088c1bf..bea15b45 100644 --- a/shared/utils/date-helper.ts +++ b/shared/utils/date-helper.ts @@ -1,13 +1,22 @@ import dayjs from 'dayjs'; import relativeTime from 'dayjs/plugin/relativeTime'; // 导入插件 import 'dayjs/locale/zh-cn'; // 导入本地化语言 +import { onLanguageChange } from '../i18n'; /** * Reference: https://day.js.org/ */ dayjs.extend(relativeTime); -dayjs.locale('zh-cn'); +dayjs.locale('zh-cn'); // 默认使用中文 +onLanguageChange((lang) => { + if (lang === 'en-US') { + dayjs.locale('en'); + return; + } + + dayjs.locale('zh-cn'); +}); /** * 是否为当天