Sum of Time using javascript

How to of sum time in javascript

01:00:00
00:30:00
00:30:00

I have time like above i want sum of given time like

sum of above time= 02:00:00

if i use javascript method setHours(),setMinutes() these function replace old time and show newly added time like :

1. new Date( new Date(0, 0, 0, 00, 00, 00, 0)).setMinutes(30)
2. new Date(new Date( new Date(0, 0, 0, 00, 00, 00, 0)).setMinutes(30)).setMinutes(30);

these above both condition result is same but i want here 00:30 + 00:30 = 01:00

. Please help thanks in advance

Answers:

Answer

Try this :

        var time1 = "01:00:00";
        var time2 = "00:30:00";
        var time3 = "00:30:00";
        
        var hour=0;
        var minute=0;
        var second=0;
        
        var splitTime1= time1.split(':');
        var splitTime2= time2.split(':');
        var splitTime3= time3.split(':');
        
        hour = parseInt(splitTime1[0])+parseInt(splitTime2[0])+parseInt(splitTime3[0]);
        minute = parseInt(splitTime1[1])+parseInt(splitTime2[1])+parseInt(splitTime3[1]);
        hour = hour + minute/60;
        minute = minute%60;
        second = parseInt(splitTime1[2])+parseInt(splitTime2[2])+parseInt(splitTime3[2]);
        minute = minute + second/60;
        second = second%60;
        
        alert('sum of above time= '+hour+':'+minute+':'+second);

Answer

Some functions to help you go back and forth between the formatted length of time and seconds as an integer:

function timestrToSec(timestr) {
  var parts = timestr.split(":");
  return (parts[0] * 3600) +
         (parts[1] * 60) +
         (+parts[2]);
}

function pad(num) {
  if(num < 10) {
    return "0" + num;
  } else {
    return "" + num;
  }
}

function formatTime(seconds) {
  return [pad(Math.floor(seconds/3600)),
          pad(Math.floor(seconds/60)%60),
          pad(seconds%60),
          ].join(":");
}

You can use them to achieve what you want:

time1 = "02:32:12";
time2 = "12:42:12";
formatTime(timestrToSec(time1) + timestrToSec(time2));
// => "15:14:24"
Answer

If you want to use a Date object for this, you can, you just have to be sure to include the current value for the unit you're changing when adding to it, like so:

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() + 30); // For the second 00:30

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

function display(msg) {
  var p = document.createElement("p");
  p.innerHTML = String(msg);
  document.body.appendChild(p);
}

Technically, of course, the first time you know getHours and getMinutes will return 0, but for consistency, best to just always include them.

Answer

This solution is perfect:

function timestrToSec(timestr) {
  var parts = timestr.split(":");
  return (parts[0] * 3600) +
         (parts[1] * 60) +
         (+parts[2]);
}

function pad(num) {
  if(num < 10) {
    return "0" + num;
  } else {
    return "" + num;
  }
}

function formatTime(seconds) {
  return [pad(Math.floor(seconds/3600)%60),
          pad(Math.floor(seconds/60)%60),
          pad(seconds%60),
          ].join(":");
}

but there is a little bug in the last function "formatTime" !

return [pad(Math.floor(seconds/3600)%60), => return [pad(Math.floor(seconds/3600)),

so without %60!! Becouse if i have to sum hour, it can be greater than 60 (H)

Answer

This work for me:

    function padnum(n){return n<10 ? '0'+n : n}

    var time1 = "00:30";
    var time2 = "00:60";

    var minute=0;
    var second=0;

    var splitTime1= time1.split(':');
    var splitTime2= time2.split(':');

    minute = parseInt(parseInt(splitTime1[0]))+parseInt(splitTime2[0]);
    second = parseInt(parseInt(splitTime1[1]))+parseInt(splitTime2[1]);

    minute = minute + second/60;
    minute =parseInt(minute);
    second = second%60;

    minute = padnum(minute);
    second = padnum(second);        

    alert('sum of above time= '+minute+':'+second);
Answer

Here is a function with error handling included.

Even though it's a big function it results in an useful one-liner. Just pass an array with values and you're good to go.

function sumMinutes(values) {

  const validate = time => {
    if (time > 59 || time < 0) {
      throw new Error(
        "Hours, minutes and seconds values have to be between 0 and 59."
      );
    }
    return time;
  };

  const seconds = values
    .map(e => validate(Number(e.split(":").reverse()[0])))
    .reduce((a, b) => a + b);

  let minutes = values
    .map(e => Number(e.split(":").reverse()[1]))
    .reduce((a, b) => a + b);

  let hours = values
    .map(e =>
      e.split(":").reverse()[2] ? Number(e.split(":").reverse()[2]) : 0
    )
    .reduce((a, b) => a + b);

  minutes *= 60;
  hours *= 3600;

  let result = new Date((hours + minutes + seconds) * 1000)
    .toISOString()
    .substr(11, 8);

  return result.split(":").reverse()[2] === "00" ? result.slice(3) : result;
}

/* examples */
const seconds = ["00:03", "00:9"];
const mins = ["01:20", "1:23"];
const hours = ["00:03:59", "02:05:01"];
const mix = ["00:04:58", "10:00"];

console.log(sumMinutes(seconds)); //'00:12'
console.log(sumMinutes(mins)); //'02:43'
console.log(sumMinutes(hours)); //'02:09:00'
console.log(sumMinutes(mix)); //'14:58'

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.