-1

I am developing a web-based application to capture total time of playlist of video. my main problem is that I don't know how can I calculate the total time from an array e.g: 30:00 + 30:00 = 01:00. Time is in mm:ss output I need in hh:mm

var time = ["13:24", "4:28", "7:29"];

for (k in time){
    add(time[k].split(":"));
}
Mikul Gohil
  • 583
  • 1
  • 7
  • 14

2 Answers2

2

An example of what you could do.

// assuming num will always be positive
function zeroPad(num) {
  var str = String(num);
  if (str.length < 2) {
    return '0' + str;
  }

  return str;
}

// assuming your time strings will always be (H*:)(m{0,2}:)s{0,2} and never negative
function totalTimeString(timeStrings) {
  var totals = timeStrings.reduce(function (a, timeString) {
    var parts = timeString.split(':');
    var temp;
    if (parts.length > 0) {
      temp = Number(parts.pop()) + a.seconds;
      a.seconds = temp % 60;
      if (parts.length > 0) {
        temp = (Number(parts.pop()) + a.minutes) + ((temp - a.seconds) / 60);
        a.minutes = temp % 60;
        a.hours = a.hours + ((temp - a.minutes) / 60);
        if (parts.length > 0) {
          a.hours += Number(parts.pop());
        }
      }
    }

    return a;
  }, {
    hours: 0,
    minutes: 0,
    seconds: 0
  });

  // returned string will be HH(H+):mm:ss
  return [
    zeroPad(totals.hours),
    zeroPad(totals.minutes),
    zeroPad(totals.seconds)
  ].join(':');
}

var result1 = totalTimeString([
  '13:24',
  '4:28',
  '7:29'
]);

console.log(result1);

var result2 = totalTimeString([
  '13:24:06',
  '4:28:46',
  '17:29:11'
]);

console.log(result2);
Xotic750
  • 22,914
  • 8
  • 57
  • 79
1

Here is the good example for you...

keep your above loop and slip it into Hours and Minutes and assign it as per below dt.setHours and Minutes

this will be more helpful

var dt = new Date(0, 0, 0, 0, 0, 0, 0);
dt.setHours(dt.getHours() + 1);      // For the 01:00
dt.setMinutes(dt.getMinutes() + 30); // For the first 00:30
dt.setMinutes(dt.getMinutes()+ 25); // For the second 00:30


display(dt.getHours() + " : " + dt.getMinutes());

function display(msg) {
  var p = document.createElement("p");
  p.innerHTML = String(msg);
  document.body.appendChild(p);
}
Anup Shah
  • 167
  • 1
  • 13