如何从其他时间减去时间 [英] How do I substract time from another time

查看:76
本文介绍了如何从其他时间减去时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有两个包含特定时间的字符串。喜欢:



one =04:15:00

two =00:30:00



结果应该是03:45:00



如何在JavaScript中实现这一点?



我尝试了什么:



我试图获得一个新的Date-Object并使用getHour(),getMinutes()和getSeconds()。但目前我不知道接下来的步骤是什么。

I have currently two strings what containig a specific time. Like:

one = "04:15:00"
two = "00:30:00"

The result should be "03:45:00"

How can i realize this in JavaScript?

What I have tried:

I tried to get a new Date-Object and used getHour(), getMinutes() and getSeconds(). But currently i don't know what are the next steps.

推荐答案

有很多种方法可以做到这一点。这里只是一个其中:



There are many possible ways to do that. Here's just one of them:

String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); 
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours < 10) { hours = "0" + hours; }
    if (minutes < 10) { minutes = "0" + minutes; }
    if (seconds < 10) { seconds = "0" + seconds; }
    var time = hours + ':' + minutes + ':' + seconds;
    return time;
}


function dateDiff(time1, time2) {
    var t1 = new Date();
    var parts = time1.split(":");
    t1.setHours(parts[0], parts[1], parts[2], 0);
    var t2 = new Date();
    parts = time2.split(":");
    t2.setHours(parts[0], parts[1], parts[2], 0);

    return (parseInt(Math.abs(t1.getTime() - t2.getTime()) / 1000)).toString().toHHMMSS();
}

var one = "04:15:00";
var two = "00:30:00";

alert(dateDiff(one,two)); //outputs "03:45:00"





现场演示:时差演示 - JSFiddle [ ^ ]


这篇关于如何从其他时间减去时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆