8

我的时间值如下 starttime 像:09:00:00 ,endTime 像:10:00:00 ;这里不需要日期值。所以这个值需要计算差异并转换为小时和分钟,秒。

我曾尝试过:

var test = new Date().getTime(startTime); 
var test1 = new Date().getTime(endTime);
var total = test1 - test;

一些时间NaN1111111一些数字格式。

如何转换为 HH:MM:SS 或任何其他方式来查找时差。

4

3 回答 3

15

您可以取不同的时间值:

var diff = test1.getTime() - test.getTime(); // this is a time in milliseconds
var diff_as_date = new Date(diff);
diff_as_date.getHours(); // hours
diff_as_date.getMinutes(); // minutes
diff_as_date.getSeconds(); // seconds
于 2013-10-25T07:36:58.063 回答
9

    var startTime = "09:00:00";
    var endTime = "10:30:00";
    
    var todayDate = moment(new Date()).format("MM-DD-YYYY"); //Instead of today date, We can pass whatever date        

    var startDate = new Date(`${todayDate} ${startTime}`);
    var endDate = new Date(`${todayDate } ${endTime}`);
    var timeDiff = Math.abs(startDate.getTime() - endDate.getTime());

    var hh = Math.floor(timeDiff / 1000 / 60 / 60);   
    hh = ('0' + hh).slice(-2)
   
    timeDiff -= hh * 1000 * 60 * 60;
    var mm = Math.floor(timeDiff / 1000 / 60);
    mm = ('0' + mm).slice(-2)

    timeDiff -= mm * 1000 * 60;
    var ss = Math.floor(timeDiff / 1000);
    ss = ('0' + ss).slice(-2)
    
    alert("Time Diff- " + hh + ":" + mm + ":" + ss);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.28.0/moment.min.js"></script>

于 2013-10-25T07:37:36.583 回答
1
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);

// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
   hours = hours + 24;

return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
于 2019-03-22T06:57:19.123 回答