116 lines
2.1 KiB
TypeScript
116 lines
2.1 KiB
TypeScript
import dayjs from 'dayjs'
|
|
|
|
export function formatPostTime(input?: dayjs.ConfigType): string {
|
|
if (!input)
|
|
return ''
|
|
|
|
const time = dayjs(input)
|
|
if (!time.isValid())
|
|
return ''
|
|
|
|
const now = dayjs()
|
|
|
|
const diffSeconds = now.diff(time, 'second')
|
|
if (diffSeconds < 0) {
|
|
// 未来时间兜底
|
|
return time.format('YYYY年MM月DD日')
|
|
}
|
|
|
|
// 1 分钟内
|
|
if (diffSeconds < 60) {
|
|
return '刚刚'
|
|
}
|
|
|
|
const diffMinutes = now.diff(time, 'minute')
|
|
if (diffMinutes < 60) {
|
|
return `${diffMinutes}分钟前`
|
|
}
|
|
|
|
const diffHours = now.diff(time, 'hour')
|
|
if (diffHours < 24) {
|
|
return `${diffHours}小时前`
|
|
}
|
|
|
|
const diffDays = now.diff(time, 'day')
|
|
if (diffDays < 14) {
|
|
return `${diffDays}天前`
|
|
}
|
|
|
|
// 本年
|
|
if (time.year() === now.year()) {
|
|
return time.format('MM月DD日')
|
|
}
|
|
|
|
// 非本年
|
|
return time.format('YYYY年MM月DD日')
|
|
}
|
|
|
|
export function formatCommentTime(input?: dayjs.ConfigType): string {
|
|
if (!input)
|
|
return ''
|
|
|
|
const time = dayjs(input)
|
|
if (!time.isValid())
|
|
return ''
|
|
|
|
const now = dayjs()
|
|
const diffSeconds = now.diff(time, 'second')
|
|
|
|
// 未来时间兜底
|
|
if (diffSeconds < 0) {
|
|
return time.format('YYYY-MM-DD HH:mm')
|
|
}
|
|
|
|
// 1 分钟内
|
|
if (diffSeconds < 60) {
|
|
return '刚刚'
|
|
}
|
|
|
|
const diffMinutes = now.diff(time, 'minute')
|
|
if (diffMinutes < 60) {
|
|
return `${diffMinutes}分钟前`
|
|
}
|
|
|
|
const diffHours = now.diff(time, 'hour')
|
|
if (diffHours < 24) {
|
|
return `${diffHours}小时前`
|
|
}
|
|
|
|
const diffDays = now.diff(time, 'day')
|
|
if (diffDays < 7) {
|
|
return `${diffDays}天前`
|
|
}
|
|
|
|
// 本年
|
|
if (time.year() === now.year()) {
|
|
return time.format('MM-DD HH:mm')
|
|
}
|
|
|
|
// 非本年
|
|
return time.format('YYYY-MM-DD HH:mm')
|
|
}
|
|
|
|
type DateFormat
|
|
= | 'YYYY'
|
|
| 'MM'
|
|
| 'DD'
|
|
| 'YYYY-MM'
|
|
| 'YYYY-MM-DD'
|
|
| 'YYYY-MM-DD HH:mm'
|
|
| 'YYYY-MM-DD HH:mm:ss'
|
|
| 'YYYY年MM月DD日'
|
|
|
|
export function formatDate(
|
|
input?: dayjs.ConfigType,
|
|
format: DateFormat = 'YYYY-MM-DD',
|
|
): string {
|
|
if (!input)
|
|
return ''
|
|
|
|
const date = dayjs(input)
|
|
if (!date.isValid())
|
|
return ''
|
|
|
|
return date.format(format)
|
|
}
|