From 90b49106f09f9da965a624f1639d64aef4de4145 Mon Sep 17 00:00:00 2001 From: baka-gourd <36119339+baka-gourd@users.noreply.github.com> Date: Sat, 28 May 2022 20:53:24 +0800 Subject: [PATCH] add chs date format --- src/package/utils/ago.ts | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/package/utils/ago.ts b/src/package/utils/ago.ts index 9cefe6efd..4e180c6c8 100644 --- a/src/package/utils/ago.ts +++ b/src/package/utils/ago.ts @@ -28,6 +28,8 @@ export function ago( { ge: 30 * SECOND, divisor: SECOND, unit: 'seconds' }, { ge: 0, divisor: 1, text: 'just now' }, ] + // must get language from browser + const firstLanguage = navigator.language const now = typeof nowDate === 'object' ? nowDate.getTime() : new Date(nowDate).getTime() const diff = now - (typeof date === 'object' ? date : new Date(date)).getTime() const diffAbs = Math.abs(diff) @@ -35,6 +37,9 @@ export function ago( if (diffAbs >= interval.ge) { const x = Math.round(Math.abs(diff) / interval.divisor) const isFuture = diff < 0 + if (firstLanguage === 'zh-CN' || firstLanguage === 'zh') { + return chs_format(x, isFuture, interval.unit as Unit) + } return interval.unit ? rft.format(isFuture ? x : -x, interval.unit as Unit) : interval.text } } @@ -55,3 +60,54 @@ type Unit = | 'months' | 'year' | 'years' + +type ChsUnit = '秒' | '分' | '小时' | '天' | '周' | '月' | '年' + +/** + * Convert unit to chinese unit + * @param unit + * @returns {ChsUnit} + */ +function convertUnitToChsUnit(unit: Unit): ChsUnit { + switch (unit) { + case 'second': + case 'seconds': + return '秒' + case 'minute': + case 'minutes': + return '分' + case 'hour': + case 'hours': + return '小时' + case 'day': + case 'days': + return '天' + case 'week': + case 'weeks': + return '周' + case 'month': + case 'months': + return '月' + case 'year': + case 'years': + return '年' + } +} + +/** + * The default converter provided by js does not conform to Chinese typography. + * @param value date value + * @param isFuture + * @param unit + * @returns {string} + */ +function chs_format(value: number, isFuture: boolean, unit: Unit): string { + const chsUnit = convertUnitToChsUnit(unit) + let quantifier = '' + switch (chsUnit) { + case '月': + case '小时': + quantifier = '个' + } + return `${value} ${quantifier}${chsUnit}${isFuture ? '后' : '前'}` +} \ No newline at end of file