Skip to content Skip to sidebar Skip to footer

Add Multiple Datetime Duration Strings Together Using Javascript To Get Total Duration

I have an HTML Table used to generate a Calendar which shows TimeClock entries for each day a user has worked and clocked in and out of the system. Each day also shows the total t

Solution 1:

With JQuery and Javascript its easily possible. Please have a look at below code.

$(document).ready(function(){
    var pad = function(num) { return ("0"+num).slice(-2); }
    var totalSeconds = 0;
    $("li").each(function(){
        var currentDuration = $(this).text();
        currentDuration = currentDuration.split(":");
        var hrs = parseInt(currentDuration[0],10);
        var min = parseInt(currentDuration[1],10);
        var sec = parseInt(currentDuration[2],10);
        var currDurationSec = sec + (60*min) + (60*60*hrs); 
        totalSeconds +=currDurationSec;
    });
    

    var hours = Math.floor(totalSeconds / 3600);
	totalSeconds %= 3600;
	var minutes = Math.floor(totalSeconds / 60);
	var seconds = totalSeconds % 60;
  $(".totalVal").text(pad(hours)+":"+pad(minutes)+":"+pad(seconds));
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><ul><li>03:31:23</li><li>04:21:56</li><li>04:08:42</li><li>03:31:17</li><li>04:10:59</li><li>02:48:21</li><li>04:26:11</li><li>00:00:39</li><li>03:41:37</li></ul><divid="totalTime">Total Time:<spanclass="totalVal"></span></div>

Solution 2:

This is a little overkill, but shows how to use map and reduce.

/** Calculate the number of seconds from HH:MM:SS **/functiongetSeconds(time) {
  var parts = time.split(":");
  returnparseInt(parts[0], 10) * 3600 + parseInt(parts[1], 10) * 60 + parseInt(parts[2], 10);
}

//select all the elementsvar totalSeconds = $("a.cal-punch-total-time")
    .map( function(ind, elem) { //convert the jQuery object into the array  var text = $(elem).text();  //get the text from the anchorreturngetSeconds(text);    //set the index to the total seconds
    })
    .get()  //gets the array out of the jQuery object
    .reduce( function(runningTotal, currentValue){  //Now to combine all the values into onereturn runningTotal + currentValue;  //sum up the values
    },0);  //The initial starting vaule//Now get the hour, minutes, and seconds from the total secondsvar hours = parseInt( totalSeconds / 3600 );
var minutes = parseInt( totalSeconds / 60 ) % 60;
var seconds = totalSeconds % 60;

//left pad numbers less than tenif(hours<10) hours = "0" + hours;
if(minutes<10) minutes = "0" + minutes;
if(seconds<10) seconds = "0" + seconds;


$("#out").html("Total Time: " + (hours + ":" + minutes + ":" + seconds));
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><aclass="cal-punch-total-time">03:31:23</a><aclass="cal-punch-total-time">04:21:56</a><aclass="cal-punch-total-time">04:08:42</a><aclass="cal-punch-total-time">03:31:17</a><aclass="cal-punch-total-time">04:10:59</a><aclass="cal-punch-total-time">02:48:21</a><aclass="cal-punch-total-time">04:26:11</a><aclass="cal-punch-total-time">00:00:39</a><aclass="cal-punch-total-time">03:41:37</a><divid="out"></div>

Solution 3:

Try this:

functionhhmmssToSeconds(str)  {
    var arr = str.split(':').map(Number);
    return (arr[0] * 3600) + (arr[1] * 60) + arr[2];
};

functionsecondsToHHMMSS(seconds) {
    var hours = parseInt(seconds / 3600, 10),
        minutes = parseInt((seconds / 60) % 60, 10),
        seconds = parseInt(seconds % 3600 % 60, 10);

    return [hours, minutes, seconds].map(function (i) { return i.toString().length === 2 ? i : '0' + i; }).join(':');
}

Then:

var t1 = hhmmssToSeconds('40:50:40'),
    t2 = hhmmssToSeconds('04:12:30');

var result = secondsToHHMMSS(t1 + t2); // '45:03:10'

Solution 4:

You can split your DateTime strings into arrays.

totalTimeValue = $(this).text().split(':'); //from '03:10:30' to ['03','10','30']

Then loop through your array and coerce each string to a number.

totalTimeValue.forEach(function(val,idx){
    totalWeekTimeValue[idx] += Number(val);
  });

This will leave you with an array of values for totalWeekTime that you can format/recalculate and rejoin if needed.

totalWeekTimeValue.join(':'); //[3:10:30]

http://codepen.io/hirechrismeyers/pen/ZbVVgr

Post a Comment for "Add Multiple Datetime Duration Strings Together Using Javascript To Get Total Duration"