NodeJS 时差问题

2g32fytz  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(152)

function timeDifference(laterdate, earlierdate) { var difference = laterdate.getTime() - earlierdate.getTime(); var daysDifference = Math.floor(difference/1000/60/60/24); difference -= daysDifference*1000*60*60*24 var hoursDifference = Math.floor(difference/1000/60/60); difference -= hoursDifference*1000*60*60 var minutesDifference = Math.floor(difference/1000/60); difference -= minutesDifference*1000*60 var secondsDifference = Math.floor(difference/1000); total = hoursDifference + ":" + minutesDifference + ":" + secondsDifference; return total; }我的代码中有两个时间(startTime,endTime),我正在从数据库中获取它们。startTime = '2022-12-13 10:00:48'和endTime = '2022-12-13 10:01:02'。我希望以HH:MM:SS格式获取两个时间之间的差值
我需要时差,但是当我试图得到时差时,我得到了NaN。

hc8w905p

hc8w905p1#

javaScript是一种无类型语言,这意味着它在某些情况下非常灵活,但在另一方面,您可能会发现自己会遇到意想不到结果,特别是当您没有实现适当的控件时。
在您代码中,您试图通过连接数字和字符串来返回一些数学运算:

total = hoursDifference + ":" + minutesDifference + ":" +secondsDifference;

但是你应该使用反勾号来达到预期的效果:

`${hoursDifference}:${minutesDifference}:${secondsDifference}`
function timeDifference(laterdate, earlierdate) {
    var difference = laterdate.getTime() - earlierdate.getTime();
    var daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
    difference -= daysDifference * 1000 * 60 * 60 * 24
    var hoursDifference = Math.floor(difference / 1000 / 60 / 60);
    difference -= hoursDifference * 1000 * 60 * 60
    var minutesDifference = Math.floor(difference / 1000 / 60);
    difference -= minutesDifference * 1000 * 60
    var secondsDifference = Math.floor(difference / 1000);
    total =  `${hoursDifference}:${minutesDifference}:${secondsDifference}`;
    return total;
}

let laterdate = new Date("2022-12-13 10:00:48")
let earlierdate = new Date("2022-12-13 10:00:47")
console.log(timeDifference(laterdate,earlierdate))

相关问题