Click here to Skip to main content
15,889,542 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Updated 16-Nov-18 5:05am

1 solution

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

JavaScript
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"


Live demo: Time Difference Demo - JSFiddle[^]
 
Share this answer
 
v3
Comments
Sascha Manns 18-Nov-18 4:13am    
@Vincent: Many thanks, it works perfectly :-)
Vincent Maverick Durano 18-Nov-18 12:47pm    
Welcome! Glad to be of help. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900