获取时间差函数
~~~
/**
* 时间差计算
* @param {String} time 终止时间(格式为时间戳)
* @returns {Array} ["相差天数", "相差小时", "相差分钟", "相差秒数"]
*/
function getTimeDeffer(time) {
const interval = new Date().getTime() - time
const days = Math.floor(interval / (24 * 3600 * 1000))
//计算出小时数
let leaveTime = interval % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
const hours = Math.floor(leaveTime / (3600 * 1000))
//计算相差分钟数
leaveTime = leaveTime % (3600 * 1000) //计算小时数后剩余的毫秒数
const minutes = Math.floor(leaveTime / (60 * 1000))
//计算相差秒数
leaveTime = leaveTime % (60 * 1000) //计算分钟数后剩余的毫秒数
const seconds = Math.round(leaveTime / 1000)
return [days, hours, minutes, seconds]
}
~~~
调用方法
~~~
const older = "2019-09-09 14:50:05"
// 先转换为时间戳格式
const time = new Date(older).getTime()
console.error('the deffer time', getTimeDeffer(time))
~~~