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

血红的双手。 提交于 2020-06-18 10:38:45

问题


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


回答1:


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



回答2:


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))



回答3:


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)



回答4:


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;
};


来源:https://stackoverflow.com/questions/26580509/calculate-time-difference-between-two-date-in-hhmmss-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!