我的时间值如下 starttime like:09:00:00, 结束时间如:10:00:00; 这里不需要日期值。 所以这个值需要计算差值并转换成小时和分钟,秒。
我曾尝试过:
var test = new Date().getTime(startTime);
var test1 = new Date().getTime(endTime);
var total = test1 - test;
有时我会得到NaN
和1111111
某种数字格式。
如何转换为HH:MM:SS,或任何其他寻找时差的方法。
答案 0 :(得分:12)
您可以对时间值进行区分:
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
答案 1 :(得分:5)
var startTime = "09:00:00";
var endTime = "10:00:00";
var startDate = new Date("January 1, 1970 " + startTime);
var endDate = new Date("January 1, 1970 " + endTime);
var timeDiff = Math.abs(startDate - endDate);
var hh = Math.floor(timeDiff / 1000 / 60 / 60);
if(hh < 10) {
hh = '0' + hh;
}
timeDiff -= hh * 1000 * 60 * 60;
var mm = Math.floor(timeDiff / 1000 / 60);
if(mm < 10) {
mm = '0' + mm;
}
timeDiff -= mm * 1000 * 60;
var ss = Math.floor(timeDiff / 1000);
if(ss < 10) {
ss = '0' + ss;
}
alert("Time Diff- " + hh + ":" + mm + ":" + ss);
答案 2 :(得分:0)
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;
}