Files
uniapp-im-shop/utils/dateUtils.js
2026-01-13 01:12:29 +08:00

83 lines
2.4 KiB
JavaScript
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.
/** 日期格式化 YYYY-MM-DD */
export const formatDate = date => {
const d = new Date(date)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0') // 月份从0开始
const day = String(d.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
/** 日期格式化:月.日 */
export const formatMonthDay = date => {
// 统一处理为 Date 对象
const d = new Date(date)
// 检查是否是有效日期
if (isNaN(d.getTime())) {
console.error('Invalid date:', date)
return '--.--'
}
const month = String(d.getMonth() + 1).padStart(2, '0') // getMonth() 是 0-11
const day = String(d.getDate()).padStart(2, '0')
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] // 或使用更美观的格式
}
}