3

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

BomberMan
  • 1,094
  • 3
  • 13
  • 33
  • one easy way is to use ISO strings, which work up to 24 hours. for 333 seconds: new Date( 333 * 1000 ).toISOString().split("T").pop().split(".")[0]; which looks like "00:05:33" – dandavis Oct 27 '14 at 03:08
  • 1
    (date2.valueOf() - date1.valueOf()) / 1000 == number of seconds difference... – beauXjames Oct 27 '14 at 03:09
  • why don't you just create a start date object on init and a new one in interval timer – charlietfl Oct 27 '14 at 03:18
  • 1
    @beauXjames—if using date objects, *(date2 - date1)/1000* will do. ;-) – RobG Oct 27 '14 at 03:20
  • @RobG -- true, but if he's watching the variables in devtools he can see the ms and skip the rendered date format -- kept it as a comment to avoid the critique -- ;P – beauXjames Oct 27 '14 at 20:32

5 Answers5

14

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
RobG
  • 142,382
  • 31
  • 172
  • 209
3

I think there is a simpler solution.

function dateDiffToString(a, b){

    // make checks to make sure a and b are not null
    // and that they are date | integers types

    diff = Math.abs(a - b);

    ms = diff % 1000;
    diff = (diff - ms) / 1000
    ss = diff % 60;
    diff = (diff - ss) / 60
    mm = diff % 60;
    diff = (diff - mm) / 60
    hh = diff % 24;
    days = (diff - hh) / 24

    return days + ":" + hh+":"+mm+":"+ss+"."+ms;

}

var today = new Date()
var yest = new Date()
    yest = yest.setDate(today.getDate()-1)

console.log(dateDiffToString(yest, today))
sh87
  • 1,063
  • 10
  • 12
  • This is a perfect solution, provided both the dateTime objects should use the same time zone. – BuzzR Feb 03 '20 at 11:51
3
const dateDiffToString = (a, b) => {
  let diff = Math.abs(a - b);

  let ms = diff % 1000;
  diff = (diff - ms) / 1000;
  let s = diff % 60;
  diff = (diff - s) / 60;
  let m = diff % 60;
  diff = (diff - m) / 60;
  let h = diff;

  let ss = s <= 9 && s >= 0 ? `0${s}` : s;
  let mm = m <= 9 && m >= 0 ? `0${m}` : m;
  let hh = h <= 9 && h >= 0 ? `0${h}` : h;

  return hh + ':' + mm + ':' + ss;
};
Robin Wieruch
  • 14,900
  • 10
  • 82
  • 107
1

This may be the simple answer

var d1 = new Date(2014,10,11,1,43,28);
var d2 = new Date(2014,10,11,2,53,58);
var date = new Date(d2-d1);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
console.log(day + ":" + hour + ":" + min + ":" + sec)
GAURAV
  • 647
  • 6
  • 18
0

More intuitive and easier to read.

function hmsToSeconds(t) {
    const [hours, minutes, seconds] = t.split(':')
    return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds)
  }

function secondsToHMS(secs) {
    return new Date(secs * 1000).toISOString().substr(11, 8)
  }

var startTime = '01:43:28';
var endTime = '12:22:46';

console.log(secondsToHMS(hmsToSeconds(endTime) - hmsToSeconds(startTime))); //10:39:18
Yogesh Yadav
  • 723
  • 6
  • 21