如何将分钟转换为小时和分钟,减去时间(减去时间值) [英] how to convert the minutes into hours and minutes with subtracted time(subtracted time values)
问题描述
我想减去两种不同的24小时时间格式。
I want to subtract the two different 24 hours time format.
我曾尝试过以下内容:
var startingTimeValue = 04:40;
var endTimeValue = 00:55;
var hour = startingTimeValue.split(":");
var hour1 = endTimeValue.split(":");
var th = 1 * hour[0] - 1 * hour1[0];
var tm = 1 * hour[1] - 1 * hour1[1];
var time = th+":"+tm;
如果第二分钟不大于第一分钟,此代码工作正常。但是其他情况下它将返回减去值。
This code is working fine if second minutes is not greater than the first.but other case it will return minus values.
以上代码示例值结果:
time1 : 04:40
time2 : 00:55
结果应为:03:45 (h:mi)格式。
但是现在我得到了04:-5的负值。
The result should be : 03:45 (h:mi) format. But right now I am getting 04:-5 with minus value.
我试过这个链接:从计算时间javascript中扣除分钟数但这不适用于00:00格式。
那么如何计算结果值并转换成小时和分钟?
I had tried with the link as : subtract minutes from calculated time javascript but this is not working with 00:00 format. So how to calculate the result value and convert into hours and minutes?
推荐答案
我会尝试类似以下内容。
我看到它的方式,最好将它分解为一个普通单位然后做简单的数学运算。
I would try something like the following. The way I see it, it is always better to break it down to a common unit and then do simple math.
function diffHours (h1, h2) {
/* Converts "hh:mm" format to a total in minutes */
function toMinutes (hh) {
hh = hh.split(':');
return (parseInt(hh[0], 10) * 60) + parseInt(hh[1], 10);
}
/* Converts total in minutes to "hh:mm" format */
function toText (m) {
var minutes = m % 60;
var hours = Math.floor(m / 60);
minutes = (minutes < 10 ? '0' : '') + minutes;
hours = (hours < 10 ? '0' : '') + hours;
return hours + ':' + minutes;
}
h1 = toMinutes(h1);
h2 = toMinutes(h2);
var diff = h2 - h1;
return toText(diff);
}
这篇关于如何将分钟转换为小时和分钟,减去时间(减去时间值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!