mirror of https://github.com/msgbyte/tailchat
refactor: 消息显示时间函数
parent
b3d58efd74
commit
6e65712de6
@ -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');
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue