javascript 时差并在javascript中转换为小时和分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19583557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Time difference and convert into hours and minutes in javascript
提问by Dharmaraja.k
I am having the time values as follows starttime like : 09:00:00 , endTime like : 10:00:00 ; here no date value is needed. so this values need to calculate difference and convert into hours and minutes,seconds.
我的时间值如下开始时间:09:00:00,结束时间:10:00:00;这里不需要日期值。所以这个值需要计算差异并转换为小时和分钟,秒。
I had tried with :
我曾尝试过:
var test = new Date().getTime(startTime);
var test1 = new Date().getTime(endTime);
var total = test1 - test;
Some time am getting NaN
and 1111111
some digit format.
一些时间得到NaN
和1111111
一些数字格式。
How can I convert into HH:MM:SS, or any other way to find time difference.
我怎样才能转换成 HH:MM:SS 或任何其他方式来找到时差。
回答by SheetJS
You can take a difference of the time values:
您可以采用时间值的差异:
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
回答by hongchae
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);
回答by Vijaya Varma Lanke
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;
}