4

Looking to add time together within javascript.

I have never written any javascript, and as such am struggling with the way to progress.

I have got to add say 4:00 (4 hours) to 12:44 (Current Time) Is this possible within javascript?

The answer should report back 16:44

If so, how would I go about it?

Thanks

ggorlen
  • 44,755
  • 7
  • 76
  • 106
JoeM
  • 93
  • 1
  • 3
  • 13

5 Answers5

8

If you break it down into a couple of small helper functions, it's not too hard:

// Convert a time in hh:mm format to minutes
function timeToMins(time) {
  var b = time.split(':');
  return b[0]*60 + +b[1];
}

// Convert minutes to a time in format hh:mm
// Returned value is in range 00  to 24 hrs
function timeFromMins(mins) {
  function z(n){return (n<10? '0':'') + n;}
  var h = (mins/60 |0) % 24;
  var m = mins % 60;
  return z(h) + ':' + z(m);
}

// Add two times in hh:mm format
function addTimes(t0, t1) {
  return timeFromMins(timeToMins(t0) + timeToMins(t1));
}

console.log(addTimes('12:13', '01:42')); // 13:55
console.log(addTimes('12:13', '13:42')); // 01:55
console.log(addTimes('02:43', '03:42')); // 06:25
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Where does t0 and t1 come from?? – JoeM Sep 10 '14 at 12:59
  • 3
    They are the times passed in the call, see the examples. – RobG Sep 10 '14 at 22:56
  • addTimes("142:47", "22:11"); Doing this results in "20:58", which isn't correct. Is it supposed to work like that or am I missing something here? – Minasie Shibeshi Feb 15 '21 at 09:09
  • @MinasieShibeshi—per code comments, times are returned in the range 00:00 to 24:00. If you don’t want that, remove `% 24` from the *h* assignment. – RobG Feb 15 '21 at 09:42
7

Take a look at moment.js - an excellent library for managing all kinds of time related functionality - momentjs.com

Later addition to answer:

You mention your are a newbie with JavaScript so here is a simple working example of your problem using moment.js - this example assumes the file and moment.js are in the same folder. Check out the docs on the moment.js for all the formatting options. Good luck.

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Time</title>
<script src="moment.js"></script>
</head>

<body>

   <script>

   //add 4 hours to the stated time
   var theFutureTime = moment().hour('12').minute('44').add(4,'hours').format("HH:mm");

   console.log(theFutureTime);  // prints 16:44

  </script>

</body>

Charles Wyke-Smith
  • 2,479
  • 3
  • 17
  • 16
  • +1 from me, although the direct problem you are working on isn't toooo tricky. Times and dates in general are notoriously tricky in JavaScript. If it's a learning exercise, sure create the code by hand. But if it's production code I'd simply use a date time library. momentjs is great or http://www.datejs.com/ as an alternative. – Alex KeySmith Sep 10 '14 at 12:24
1

Using moment.js you can convert hh:mm to minutes and add them.

Example:

moment.duration("02:45").asMinutes() + moment.duration("02:15").asMinutes()

Result: 300 mins

So, you can convert minutes to hh:mm:

function timeConvert1(data) {
  var minutes = data % 60;
  var hours = (data – minutes) / 60;  
  return (hours + “:” + minutes);
}
Styx
  • 9,863
  • 8
  • 43
  • 53
AquariusPotter
  • 156
  • 2
  • 10
  • And if you don't like **timeConvert1** function, you can use: **moment.duration(sum,'minutes').hours()** and **moment.duration(sum,'minutes').minutes()** to get hours and minutes. You can use **("0"+number).slice(-2)** to convert **1,2,...,23** to **01,02,...,22,23** Ex: **("0"+(moment.duration(sum,'minutes').hours())).slice(-2)+':'+("0"+moment.duration(sum,'minutes').minutes()).slice(-2)** – AquariusPotter Dec 27 '18 at 04:30
1

For add array of time-format strings (including seconds and without counting days).

For example:

Input: times = ['00:00:10', '00:24:00']

Output 00:24:10

// Add two times in hh:mm:ss format
function addTimes(times = []) {

    const z = (n) => (n < 10 ? '0' : '') + n;

    let hour = 0
    let minute = 0
    let second = 0
    for (const time of times) {
        const splited = time.split(':');
        hour += parseInt(splited[0]);
        minute += parseInt(splited[1])
        second += parseInt(splited[2])
    }
    const seconds = second % 60
    const minutes = parseInt(minute % 60) + parseInt(second / 60)
    const hours = hour + parseInt(minute / 60)

    return z(hours) + ':' + z(minutes) + ':' + z(seconds)
}
sharonooo
  • 684
  • 3
  • 8
  • 25
0
function addHours(start, end) {
var mins= moment.duration(start).asMinutes() + moment.duration(end).asMinutes();
  function z(n){return (n<10? '0':'') + n;}
  var h = (mins/60 |0) % 24;
  var m = mins % 60;
  return z(h) + ':' + z(m);
}
Jitendra Suthar
  • 2,111
  • 2
  • 16
  • 22