Files
mversion-ui/src/hooks/useRelativeTime.ts
2026-01-05 19:28:55 +08:00

52 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// useRelativeTime.ts
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn' // 引入中文语言包
// 初始化插件和语言
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')
export function useRelativeTime() {
/**
* 核心转换函数
* @param value 时间戳、Date对象或ISO字符串
*/
const formatTime = (value: string | number | Date): string => {
if (!value) return ''
const target = dayjs(value)
const now = dayjs()
const diffSeconds = now.diff(target, 'second')
const diffDays = now.diff(target, 'day')
// 1. 极短时间内60秒内显示“刚刚”
if (diffSeconds < 60) {
return '刚刚'
}
// 2. 一天以内(显示 10分钟前, 1小时前等
if (diffDays < 1) {
return target.fromNow()
}
// 3. 超过一天但在一年以内(显示 10-27
if (diffDays < 365) {
return target.format('MM-DD HH:mm')
}
// 4. 超过一年(显示 2023-10-27
return target.format('YYYY-MM-DD')
}
// 如果你需要判断“是否超过可删除时间”比如5分钟内可删除
const canAction = (value: string | number | Date, limitMinutes: number = 5) => {
return dayjs().diff(dayjs(value), 'minute') < limitMinutes
}
return {
dayjs, // 同时也暴露原生的 dayjs 方便外部灵活使用
formatTime,
canAction
}
}