/**
* 根据传入的时间与现在的时间差
* 将时间差转成可读字符串 如:刚刚、3秒前、一小时前等等
*
* @param time 需要进行比较的毫秒级时间(毫秒 同时需要 小于 当前时间)
* @return 返回可读字符串, 大于20天的 将会直接显示日期
*/
export function timeDifference(time) {
if (time === null || time === undefined) {
return ''
}
// 获取两个日期之间相差的毫秒数
const timeDifference = Math.abs(Date.now() - time)
const days = timeDifference / 1000 / 60 / 60 / 24
const hours = timeDifference / 1000 / 60 / 60 - (24 * Math.floor(days))
const minutes = timeDifference / 1000 / 60 - (24 * 60 * Math.floor(days)) - (60 * Math.floor(hours))
const seconds = timeDifference / 1000 - (24 * 60 * 60 * Math.floor(days)) - (60 * 60 * Math.floor(hours)) - (60 * Math.floor(minutes))
// 1分钟以内(1分钟 = 60000ms)
if (timeDifference < 60000) {
// 如果是5秒内
const just = 5
if (timeDifference < 1000 * just) {
return '刚刚'
} else {
return Math.floor(seconds) + '秒前'
}
}
// 一小时内(大于 1分钟[60000ms] 小于 1小时[3600000ms])
if (timeDifference >= 60000 && timeDifference < 3600000) {
return Math.floor(minutes) + '分钟前'
}
// 一天内
if (timeDifference >= 3600000 && timeDifference < 86400000) {
return Math.floor(hours) + '小时前'
}
// 二十天内
const twentyDays = 86400000 * 20
if (timeDifference >= 86400000 && timeDifference < twentyDays) {
return Math.floor(days) + '天前'
}
return ''
}
6.(JavaScript)获取某个时间与现在的时间差
最新推荐文章于 2024-08-13 10:28:25 发布