How to sum time string in an array?

moment to string
moment add days
moment to date
moment milliseconds
moment to utc
moment set locale
moment#isafter
moment is valid

Suppose, I've an array of different time string.

let a: any = ["7:20", "5:50", "6:30"];

I want to sum up these HH:mm time strings. I am building up an app using Ionic 4 (Angular). I have already used momentjs for these. But, unfortunately yet I can't find any solution.

Update: Expected Result: 7:20 + 5:50 + 6:30 = 19:40 (HH:33)

You can treat time as moment durations that can be summed up:

const any = ['7:20', '7:52', '5:03', '1:01', '9:02', '6:00'];

const sum = any.reduce((acc, time) => acc.add(moment.duration(time)), moment.duration());

console.log([Math.floor(sum.asHours()), sum.minutes()].join(':'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

Angular 7- How to sum time string elements of two arrays?, 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])  Find three elements in an array that sum to a given value; Breadth-First Search (BFS) in 2D Matrix/2D-Array; Find the increasing OR decreasing point in an array; Two Sum Problem; Depth-First Search (DFS) in 2D Matrix/2D-Array - Iterative Solution; Given an array, Print sum of all subsets; Print maximum occurring character in a String

You could use reduce method by passing a callback function.

let arr= ["7:20", "5:50", "6:30"];
toSeconds = (str) => {
   str = str.split(':');
   return (+str[0]) * 60 + (+str[1]);  
}

toHHss = (seconds) => {
   let minutes = parseInt(seconds/60);
   seconds = seconds - minutes*60;
   return minutes + ':' + seconds;
}
let result = arr.reduce((r,elem) => r + toSeconds(elem), 0);
console.log(toHHss(result));

How to calculate total time of an array in PHP ?, This functions returns the time in h:m:s format. Syntax strtotime( string ). Example 1: This example reads the values from the array and converts it into the time  Improve this sample solution and post your code through Disqus. Previous: Write a Java program to sort a numeric array and a string array. Next: Write a Java program to print the following grid.

Vanilla Javascript implementation:

const secondsToHm = s => ({
  hours: ((s - s % 3600) / 3600) % 60, 
  minutes: ((s - s % 60) / 60) % 60, 
})

let a = ["7:20", "5:50", "6:30"];
let total = 0; 

for(let i = 0; i < a.length; i++){
  const aSlice = a[i].split(':');
  const aSeconds = (+aSlice[0]) * 60 * 60 + (+aSlice[1]) * 60;
  total += aSeconds
}

console.log(`${secondsToHm(total).hours}:${secondsToHm(total).minutes}`);

Add two string time values (HH:mm:ss) with javascript · GitHub, Add two string time values (HH:mm:ss) with javascript. *. * Usage: @param {​String} startTime String time format. * @param {String} endTime String time format​. * @returns There is a problem when sum more than 99 hours. You can fix just​  how to find duplicate strings in a string array using java, total number of strings how many time they have repeated. using java string methods using nested for loops eclipse.

A POJS solution can be very simple:

/* Add array of time strings in H:mm format
** @param {Array<string>} timeArray - Array of H:mm
** @returns {string} - sum of times in H:mm format
*/
function addTimes(timeArray) {
  let mins = timeArray.reduce((acc, time) => {
    let [h, m] = time.split(':');
    acc += h*60 + m*1;
    return acc;
  }, 0);
  return (mins/60|0) + ':' + ('0'+(mins%60)).slice(-2);
}

// Example
console.log(addTimes(["7:20", "5:03", "6:42"]));

Java program to sum the elements of an array, @author: BeginnersBook.com * @description: Get sum of array elements */ class SumOfArray{ public static void main(String args[]){ int[] array = {10, 20, 30, 40,  JavaScript: Number of given string in array Tag: javascript , arrays , count Not sure how to explain this in words, but is there any function in javascript that, when given a string , will return the number of times it occurs in an array?

You can use moment.duration() to get the number of milliseconds for each time string in the array, and add them.

a.reduce((acc, t) => acc.add(moment.duration(t)), moment.duration())

PHP array_sum() Function, The array_sum() function returns the sum of all the values in the array. versions prior to 4.2.1 modified the passed array itself and converted strings to numbers  This very simply starts with a sum of 0 and add each item in the array as we go: public static int findSumWithoutUsingStream(int[] array) { int sum = 0; for (int value : array) { sum += value; } return sum; } 2.2. Sum With the Java Stream API

Arrays that represent points in time - MATLAB, character array | cell array of character vectors | string array. S = sum (A,vecdim) sums the elements of A based on the dimensions specified in the vector vecdim. For example, if A is a matrix, then sum (A, [1 2]) is the sum of all elements in A, since every element of a matrix is contained in the array slice defined by dimensions 1 and 2. example.

String Processing and Information Retrieval: 16th International , Space for encoding the differential Ψ array and individual sum time under The b sequences refer to the (different) consecutive b values used in the arrays C1,  JavaScript exercises, practice and solution: Write a JavaScript function to calculate the sum of values in an array.

Convert date and time to vector of components, If t is a datetime array, then its values represent points in time. m date vectors, where m is the total number of date numbers in DateNumber . DateVector = datevec( DateString ) converts text representing dates and times to date vectors. The only tricky part in this question is that multiple consecutive digits are considered as one number. The idea is very simple. We scan each character of the input string and if a number is formed by consecutive characters of the string, we increment the result by that amount.

Comments
  • what is the result you are expecting?
  • what result you want exactly ?
  • @Praveen I am expecting, Total Hour: 19:40 (HH:mm)
  • Why shouldn't moment("7:20", "H:mm") not work?
  • @sunielkalwani 7:20 + 5:50 + 6:30 = 19:40 (Total Hours)
  • I am getting correct result from console.log(sum.asHours()); But when I convert Hours to HH:mm the result is not expected! My Sample Input time: 7:20 + 7:52 + 5:03 + 1:01 + 9:02 + 6:00 = 36:18. But it shows 12:18 which is wrong.
  • Can you please specify how do you perform conversion from a duration to 'HH:mm' format? Did you try to approach from the updated answer (that implies getting hours and minutes separately and joining them afterwards)?
  • Yes, I am just using your updated code. Can you plz check it using my above comment sample inputs? I think you can understand.
  • @AbhijitM.Abhi Sorry for the confusion, I got your point and updated the answer that uses absolute number of hours, please take a look.
  • Exactly the correct answer what I am expecting that you have done with a few lines of code. Happy Coding!
  • The toHHss function doesn't format the minutes correctly, it produces H:m whereas the OP seems to want H:mm. The seconds parameter should probably be named minutes. :-)
  • @RobG, result will hold the total number of seconds after we do sum. Then I just convert the seconds to HH:MM format