实现目的
计算出两个时间之间相差的多少小时、分钟、秒。
例如: 2023/4/26 17:10 和 2023/4/26 18:21 之间相差了 1小时10分1秒(01:10:01)
实现代码
function calculateTimeDiff(initTime, nowTime) {
// 获得相差的秒数
let defTime = moment(nowTime).diff(moment(initTime), "seconds");
// 如果相差的时间不足一分钟
if (defTime < 60) {
if (defTime < 10) {
return "00:00:0" + defTime;
} else {
return "00:00:" + defTime;
}
} else {
// 获取相差的分钟数
let min_total = Math.floor(defTime / 60);
// 获取相差的秒数
let sec =
Math.floor(defTime % 60) > 9
? Math.floor(defTime % 60)
: "0" + Math.floor(defTime % 60);
// 相差时间不足一小时
if (min_total < 60) {
return "00:" + min_total + ":" + sec;
} else {
// 计算相差的小时数
let hour_total =
Math.floor(min_total / 60) > 9
? Math.floor(min_total / 60)
: "0" + Math.floor(min_total / 60);
let min =
Math.floor(min_total % 60) > 9
? Math.floor(min_total % 60)
: "0" + Math.floor(min_total % 60);
return hour_total + ":" + min + ":" + sec;
}
}
}