如题,获取距离当前时间的时间间隔
具体精确到什么时间维度(分钟小时等),需要自行调节或者加参数
/**
* 时间格式化,获取距离现在的时间间隔(刚刚,xx分钟前,xx小时前,xx天前...xx月前...xx年前)
* @param dateTime 接收可以被new Date()方法转换的内容
* @returns {String}
*/
export const formatTimeBeforeNow = (dateTime) => {
if (!dateTime) return ''
// 获取(目标时间及当前时间的)时间戳及间隔差值
dateTime = typeof dateTime === 'string' && isNaN(dateTime) ? dateTime.replace(/-/g, '/') : dateTime
const date = new Date(dateTime)
const today = new Date()
const timeDiff = today.getTime() - date.getTime()
// 按间隔精度进行转化比较
const minuteDiff = timeDiff / 1000 / 60
if(minuteDiff < 60) return minuteDiff < 1 ? '刚刚' : `${Math.floor(minuteDiff)}分钟前`
const hourDiff = minuteDiff / 60
if(hourDiff < 24) return `${Math.floor(hourDiff)}小时前`
const dayDiff = hourDiff / 24
if(dayDiff < 30) return `${Math.floor(dayDiff)}天前`
const monthDiff = dayDiff / 30
if(monthDiff < 12) return `${Math.floor(monthDiff)}月前`
const yearDiff = monthDiff / 12
return `${Math.floor(yearDiff)}年前`
}
若有错误请指教