refactor: 消息显示时间函数

pull/13/head
moonrailgun 4 years ago
parent b3d58efd74
commit 6e65712de6

@ -10,6 +10,7 @@
"@reduxjs/toolkit": "^1.6.0",
"axios": "^0.21.1",
"crc": "^3.8.0",
"dayjs": "^1.10.6",
"formik": "^2.2.9",
"i18next": "^20.3.2",
"i18next-http-backend": "^1.2.6",

@ -0,0 +1,21 @@
import { isToday, getMessageTimeDiff } from '../date-helper';
describe('isToday', () => {
test.each([
[new Date(), true],
[new Date(new Date().setDate(new Date().getDate() - 1)), false],
])('%s => %s', (input, should) => {
expect(isToday(input)).toBe(should);
});
});
describe('getMessageTimeDiff', () => {
test.each([
[new Date(), '几秒前'],
[new Date(new Date().setMinutes(new Date().getMinutes() - 1)), '1 分钟前'],
[new Date(new Date().setHours(new Date().getHours() - 1)), '1 小时前'],
[new Date('2020-01-01T00:00:00Z'), '2020-01-01 08:00:00'],
])('%s => %s', (input, should) => {
expect(getMessageTimeDiff(input)).toBe(should);
});
});

@ -0,0 +1,26 @@
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime'; // 导入插件
import 'dayjs/locale/zh-cn'; // 导入本地化语言
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');
/**
*
*/
export function isToday(date: Date): boolean {
return dayjs(date).isSame(dayjs(), 'd');
}
/**
*
*/
export function getMessageTimeDiff(input: Date): string {
const date = dayjs(input);
if (isToday(input)) {
return date.fromNow();
} else {
return date.format('YYYY-MM-DD HH:mm:ss');
}
}

@ -2941,6 +2941,11 @@ date-fns@^2.15.0:
resolved "https://registry.npmjs.org/date-fns/-/date-fns-2.22.1.tgz#1e5af959831ebb1d82992bf67b765052d8f0efc4"
integrity sha512-yUFPQjrxEmIsMqlHhAhmxkuH769baF21Kk+nZwZGyrMoyLA+LugaQtC0+Tqf9CBUUULWwUJt6Q5ySI3LJDDCGg==
dayjs@^1.10.6:
version "1.10.6"
resolved "https://registry.npmjs.org/dayjs/-/dayjs-1.10.6.tgz#288b2aa82f2d8418a6c9d4df5898c0737ad02a63"
integrity sha512-AztC/IOW4L1Q41A86phW5Thhcrco3xuAA+YX/BLpLWWjRcTj5TOt/QImBLmCKlrF7u7k47arTnOyL6GnbG8Hvw==
debug@2.6.9, debug@^2.2.0, debug@^2.3.3:
version "2.6.9"
resolved "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"

Loading…
Cancel
Save