Break Inside
Break Inside

Reputation: 41

Sum Hours:Minutes:Seconds in Java script

how can I sum hours:minutes:seconds in JavaScript. I mean by 04:32:05 03:14:03 To get 07:46:08

Ive tried

    var time1 = "01:00:01";
    var time2 = "01:00:10";
    var time3 = "01:54:00";
    var time4 = "01:30:00";
    var time5 = "01:00:00";
    var time6 = "01:00:00";
    var time7 = "01:00:00";
    
    var hour=0;
    var minute=0;
    var second=0;
    
    var splitTime1= time1.split(':');
    var splitTime2= time2.split(':');
    var splitTime3= time3.split(':');
    var splitTime4= time4.split(':');
    var splitTime5= time5.split(':');
    var splitTime6= time6.split(':');
    var splitTime7= time7.split(':');
    
    hour = parseInt(splitTime1[0]) + parseInt(splitTime2[0])  + parseInt(splitTime3[0])  + parseInt(splitTime4[0])  + parseInt(splitTime5[0])  + parseInt(splitTime6[0]) + parseInt(splitTime7[0]) 
    minute = parseInt(splitTime1[1]) + parseInt(splitTime2[1]) + parseInt(splitTime3[1]) + parseInt(splitTime4[1]) + parseInt(splitTime5[1]) + parseInt(splitTime6[1]) + parseInt(splitTime7[1])
    hour = hour + minute/60;
    minute = minute%60;
    second = parseInt(splitTime1[2]) + parseInt(splitTime2[2]) + parseInt(splitTime3[2]) 
    + parseInt(splitTime4[2]) + parseInt(splitTime5[2]) + parseInt(splitTime6[2]) + 
    parseInt(splitTime7[2]) 
    minute = minute + second/60;
    second = second%60;
    
   console.log(hour+ ":" + minute + ":"+ second)

The output I get is 8.4:24.183333333333334:11 instad of 08:24:11 any suggestions?

Upvotes: 0

Views: 676

Answers (5)

Aleph
Aleph

Reputation: 72

The first thing you should look into is using an Array, since you have a number of objects of the same kind.

You should ideally have something like,

const times = ["04:32:05", "03:14:03", ...]

Once you have that, this problem reduces to a classic use-case for the reduce function. The reduce function operates on an array and accumulates the value of the operation every step to yield one value at the end.

Here's an example solution for your problem

const times = ["04:32:05", "03:14:03"]
//const times = ["01:00:01", "01:00:10","01:54:00","01:30:00"]

let finalSum = times.reduce((sum, curr) => {
  //Obtain the current timestamp as an array of numbers
  //[HRS, MINS, SECS]
  let currTimeStamp = curr.split(":").map(token => parseInt(token));

  //Add the current seconds to the total seconds so far
  sum[2] += currTimeStamp[2];
  //See how many minutes you got leftover as a result of that addition
  const leftOverMins = Math.floor(sum[2] / 60);
  //Mod by 60, to keep the seconds under 60
  sum[2] %= 60;

  //Add the leftover minutes to the sum operation for minutes
  sum[1] += (currTimeStamp[1] + leftOverMins);
  //Similar procedure as above
  const leftOverHours = Math.floor(sum[1] / 60);
  sum[1] %= 60;


  sum[0] += (currTimeStamp[0] + leftOverHours);
  sum[0] %= 24;

  return sum
}, [0, 0, 0])


console.log(finalSum.join(":"))

Upvotes: 1

kusama
kusama

Reputation: 389

If you want to sum of times then you should try this

var addTime = function (time1, time2) {
//   convert to ms
  var dateObject1 = new Date(time1).valueOf();
  var dateObject2 = new Date(time2).valueOf();
  
  return dateObject1 + dateObject2;
}


var time1 = new Date().setHours(4, 32, 5, 0);
var time2 = new Date().setHours(3, 14, 3, 0);

var sum = new Date(addTime(time1, time2));

var getFormatedTime = function (time) {
  return time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()
}


console.log(getFormatedTime(sum))

Upvotes: 1

Khéops
Khéops

Reputation: 46

Hello hope this answer will help you, I recommand to replace your bottom part (where you calculate) I do pretty much the same thing, but in the good order and with round to avoid decimals problems

var time1 = "01:00:01";
    var time2 = "01:00:10";
    var time3 = "01:54:00";
    var time4 = "01:30:00";
    var time5 = "01:00:00";
    var time6 = "01:00:00";
    var time7 = "01:00:00";
    
    var hour=0;
    var minute=0;
    var second=0;

    
    var splitTime1= time1.split(':');
    var splitTime2= time2.split(':');
    var splitTime3= time3.split(':');
    var splitTime4= time4.split(':');
    var splitTime5= time5.split(':');
    var splitTime6= time6.split(':');
    var splitTime7= time7.split(':');


    var allTimes = [splitTime1, splitTime2, splitTime3, splitTime4, splitTime5, splitTime6, splitTime7]

    allTimes.forEach(element => {
        hour += parseInt(element[0])
        minute += parseInt(element[1])
        second += parseInt(element[2])
    })

    minute += Math.round(second / 60); 
    second = second % 60;
    hour += Math.round(minute / 60);
    minute = minute % 60

    
   console.log(hour+ ":" + minute + ":"+ second)

Upvotes: 0

epascarello
epascarello

Reputation: 207501

The problem with your code is you are including the decimal point

hour = hour + minute/60;

you need to floor it.

hour = hour + Math.floor(minute/60);

Now how to do it without a lot of repetitive code.

function toSeconds(s) {
  const parts = s.split(':');
  return +parts[0] * 3600 + +parts[1] * 60 + +parts[2];
}

function secondsToHHMMSS(secs) {
  return Math.floor(secs / 3600).toString().padStart(2, '0') + ':' + 
         (Math.floor(secs / 60) % 60).toString().padStart(2, '0') + ':' + 
         (secs % 60).toString().padStart(2, '0');
}


const timestamps = ["01:00:01", "01:00:10", "01:54:00", "01:30:00", "01:00:00", "01:00:00", "01:00:00"];

const totalSeconds = timestamps.reduce(function(total, ts) {
  return total + toSeconds(ts); 
}, 0);

const result = secondsToHHMMSS(totalSeconds);

console.log(result);

Upvotes: 1

Deb Das
Deb Das

Reputation: 294

your making it very complex, you can reduce this by converting into Date objects and then add each date to get the sum of all dates Understanding Date and Time in JavaScript

Upvotes: 1

Related Questions