写这个需求的时候,在网上找了好久,要不就是代码过于复杂,要不就是代码格式不利于直接复制。总之,对新手不太友好。最近在整理之前写的一些公共方法的时候,看到这个,想把它整理一下。
需求:给一个过去的时间:2020-03-04 20:33:30,距离现在相隔多少天多少时多少分
公共方法如下
function handlerDateDurationCurrent (time) {
let d1 = new Date(time)
let d2 = new Date()
let cha = Math.abs(d2.getTime() - d1.getTime())
let days = parseInt(cha / (24 * 60 * 60 * 1000))
let hours = parseInt(cha % (24 * 60 * 60 * 1000) / (60 * 60 * 1000))
let mins = parseInt(cha % (60 * 60 * 1000) / (60 * 1000))
if (days) {
return `+ ${days}d ${hours}h ${mins}m`
} else if (hours) {
return `+ ${hours}h ${mins}m`
} else {
return `+ ${mins}m`
}
}
使用的时候只需要:
let preDate = '2022-05-06 02:03:04'
let result = handlerDateDurationCurrent(preDate)
console.log(result) // 30d 20h 3m