calculate time difference between two date in HH:MM:SS javascript

BomberMan picture BomberMan · Oct 27, 2014 · Viewed 10.6k times · Source

I have created one timer application in javascript. Firstly it takes the current UTC date to init timer with some reference. here's the code

on_timer: function(e) {
            var self = this;
            if ($(e.target).hasClass("pt_timer_start")) {
                var current_date = this.get_current_UTCDate();
                this.project_timesheet_db.set_current_timer_activity({date: current_date});
                this.start_interval();
                this.initialize_timer();
                this.$el.find(".pt_timer_start,.pt_timer_stop").toggleClass("o_hidden");

Now, Once timer is started and after some time span timer has some elapsed time with reference to above on_timer: function(e) function.

This function is

start_interval: function() {
            var timer_activity = this.project_timesheet_db.get_current_timer_activity();
            var self = this;
            this.intervalTimer = setInterval(function(){
                self.$el.find(".pt_duration").each(function() {
                    var el_hour = $(this).find("span.hours");
                    var el_minute = $(this).find("span.minutes");
                    var minute = parseInt(el_minute.text());
                    if(minute >= 60) {
                        el_hour.text(_.str.sprintf("%02d", parseInt(el_hour.text()) + 1));
                        minute = 0;
                    }
                    el_minute.text(_.str.sprintf("%02d", minute));
                    var el_second = $(this).find("span.seconds");
                    var seconds = parseInt(el_second.text()) + 1;
                    if(seconds > 60) {
                        el_minute.text(_.str.sprintf("%02d", parseInt(el_minute.text()) + 1));
                        seconds = 0;
                    }
                    el_second.text(_.str.sprintf("%02d", seconds));
                });
            }, 1000);
        },

Now, considering el_hour, el_minute, el_seconds How to can i count time difference between init time and current timer value in HH:MM:SS manner.

thanks in advance for help

Answer

RobG picture RobG · Oct 27, 2014

To convert H:M:S to seconds, you can use a simple function like:

// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
  var b = s.split(':');
  return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}

Then to convert seconds back to HMS:

// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
  function z(n){return (n<10?'0':'') + n;}
  var sign = secs < 0? '-':'';
  secs = Math.abs(secs);
  return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}

var a = '01:43:28';
var b = '12:22:46';

console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b)));  // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a)));  //  10:39:18

You may want to abbreviate the function names to say:

toHMS(toSec(a) - toSec(b));  // -10:39:18

Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.

Edit

The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.

If you have Date objects, you can get the difference between them in milliseconds using:

var diffMilliseconds = date0 - date1;

and convert to seconds:

var diffSeconds = diffMilliseconds / 1000;

and present as HH:MM:SS using the secondsToHMS function above:

secondsToHMS((date0 - date1) / 1000);

e.g.

var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);

console.log( secondsToHMS((d0 - d1) / 1000));  // -10:39:18