添加朋友圈功能
This commit is contained in:
@@ -23,3 +23,60 @@ export const formatMonthDay = date => {
|
||||
|
||||
return `${month}.${day}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 将时间字符串转换为相对时间描述
|
||||
* @param {string} timeStr - 后端返回的时间字符串,如 '2026-01-12 22:51:54'
|
||||
* @returns {string} 相对时间描述,如 '刚刚'、'3分钟前'、'昨天' 等
|
||||
*/
|
||||
export function formatRelativeTime(timeStr) {
|
||||
// 兼容 iOS 不支持 '-' 分隔的日期格式,需转为标准 ISO 格式
|
||||
const normalizedTimeStr = timeStr.replace(/-/g, '/')
|
||||
|
||||
const serverTime = new Date(normalizedTimeStr)
|
||||
const now = new Date()
|
||||
|
||||
// 时间差(毫秒)
|
||||
const diffMs = now - serverTime
|
||||
|
||||
// 如果时间在未来,直接返回原始时间或处理异常
|
||||
if (diffMs < 0) {
|
||||
return timeStr // 或者 return '未来时间';
|
||||
}
|
||||
|
||||
const seconds = Math.floor(diffMs / 1000)
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const days = Math.floor(hours / 24)
|
||||
|
||||
// 判断是否是今天
|
||||
const isSameDay = (date1, date2) => {
|
||||
return (
|
||||
date1.getFullYear() === date2.getFullYear() &&
|
||||
date1.getMonth() === date2.getMonth() &&
|
||||
date1.getDate() === date2.getDate()
|
||||
)
|
||||
}
|
||||
|
||||
// 判断是否是昨天
|
||||
const isYesterday = (date1, date2) => {
|
||||
const yesterday = new Date(date2)
|
||||
yesterday.setDate(date2.getDate() - 1)
|
||||
return isSameDay(date1, yesterday)
|
||||
}
|
||||
|
||||
if (seconds < 60) {
|
||||
return '刚刚'
|
||||
} else if (minutes < 60) {
|
||||
return `${minutes}分钟前`
|
||||
} else if (hours < 24 && isSameDay(serverTime, now)) {
|
||||
return `${hours}小时前`
|
||||
} else if (isYesterday(serverTime, now)) {
|
||||
return '昨天'
|
||||
} else if (days < 7) {
|
||||
return `${days}天前`
|
||||
} else {
|
||||
// 超过一周,返回原始日期(可选格式化为 YYYY-MM-DD)
|
||||
return timeStr.split(' ')[0] // 或使用更美观的格式
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user