简体   繁体   English

javascript中的时差和转换为小时和分钟

[英]Time difference and convert into hours and minutes in javascript

I am having the time values as follows starttime like: 09:00:00, endTime like: 10:00:00;我的时间值如下 starttime 像:09:00:00,endTime 像:10:00:00; here no date value is needed.这里不需要日期值。 so this values need to calculate difference and convert into hours and minutes,seconds.所以这个值需要计算差异并转换为小时和分钟,秒。

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.有时我会得到NaN1111111一些数字格式。

How can I convert into HH:MM:SS, or any other way to find time difference.如何转换为 HH:MM:SS 或任何其他方式来查找时差。

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

 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>

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;
}

in var timeDiff = Math.abs(startDate.getTime() - endDate.getTime());var timeDiff = Math.abs(startDate.getTime() - endDate.getTime()); we do not get the sign - , if endDate.getTime() is greater.如果endDate.getTime()更大,我们没有得到符号- how we can get the sign to?我们怎样才能得到标志?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM