1

I don't think I can figure this out on my own. Lets say I have a time in the string format of HH:MM:SS ex. 10:11:06 and I would like to add another time to it and return it as a string. ex. "10:11:06" + "11:00:01" would return "21:11:07"

I have gone through this site coming up with a solution of converting it to seconds and then adding them together as such:

function addTimes(start, end) {
 var a = start.split(":");
 var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 
 var b = end.split(":");
 var seconds2 = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]); 

 var date = new Date(1970,0,1);
     date.setSeconds(seconds + seconds2);

 var c = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
     return c;
     console.log(c);
}   

Yet console.log C returns an Invalid Date. Is this still a string or am I doing something wrong?

Source 1 Source 2

EDIT: (I was stupid) I had this in a recursive loop and I initialized the sum variable with a var s = 0; instead of a var s = "00:00:00";

Community
  • 1
  • 1
  • 1
    Why on Earth are you going through all of this? `new Date(1970,0,1,+a[0],+a[1],+a[2]);` – Jared Smith Mar 23 '17 at 00:05
  • In the code snipped that you've posted, `console.log(c);` will never be executed because you `return` from the function before that call. I've just tested this function and it works for the example start and end time (`10:11:06` and `11:00:01`) that you've provided but it will definitely fail if the `start` and `end` time add up to more then `24` hours. – Titus Mar 23 '17 at 00:13
  • @Titus I do have a console.log on the outside checking the function. Thank you, I just realized it might be my other code. – Amirkhanaursrk Mar 23 '17 at 00:21

2 Answers2

3

Try this

var start = "10:11:06";
var end = "10:11:06";
  var a = start.split(":");
 var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 
 var b = end.split(":");
 var seconds2 = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]); 

 var date = new Date(1970,0,1);
     date.setSeconds(seconds + seconds2);

 var c = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
console.log(c);
Harsheet
  • 728
  • 9
  • 23
-1

try

var c = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
return c;

to convert date object to time.

Loveen Dyall
  • 824
  • 2
  • 8
  • 20