我想减去两种不同的24小时时间格式。
我曾尝试过以下内容:
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;
如果第二分钟不大于第一分钟,则此代码正常工作。但在其他情况下,它将返回减去值。
以上代码示例值结果:
time1 : 04:40
time2 : 00:55
结果应为:03:45(h:mi)格式。 但是现在我得到04:-5的负值。
我尝试使用以下链接:subtract minutes from calculated time javascript但这不适用于00:00格式。 那么如何计算结果值并转换成小时和分钟?
答案 0 :(得分:3)
我会尝试以下内容。 我看待它的方式,最好将它分解为一个公共单位,然后进行简单的数学运算。
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);
}
答案 1 :(得分:2)
尝试:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
var subtractedValue = time1 - time2;
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
此解决方案使用javascript内置日期。工作原理:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
time1 , time2 是自01/01/1970 00:00:00 UTC以来的毫秒数。
var subtractedValue = time1 - time2;
subtractedValue 是以毫秒为单位的差异。
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
这些行重建日期对象以获得小时和分钟。
答案 2 :(得分:0)
答案 3 :(得分:0)
此方法可能对您有用:
function timeDiff(s,e){
var startTime = new Date("1/1/1900 " + s);
var endTime = new Date("1/1/1900 " + e);
var diff = startTime - endTime;
var result = new Date(diff);
var h = result.getUTCHours();
var m = result.getUTCMinutes();
return (h<=9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m);
}
var startingTimeValue = "04:40";
var endTimeValue = "00:55";
var formattedDifference = timeDiff(startingTimeValue,endTimeValue);