最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to sum time string in an array? - Stack Overflow

programmeradmin2浏览0评论

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)

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)

Share Improve this question edited Jan 23, 2019 at 8:58 Mihai Alexandru-Ionut 48.4k13 gold badges105 silver badges132 bronze badges asked Jan 23, 2019 at 8:45 Abhijit Mondal AbhiAbhijit Mondal Abhi 1,8295 gold badges21 silver badges38 bronze badges 6
  • 2 what is the result you are expecting? – Praveen Commented Jan 23, 2019 at 8:46
  • what result you want exactly ? – sunil kalwani Commented Jan 23, 2019 at 8:48
  • @Praveen I am expecting, Total Hour: 19:40 (HH:mm) – Abhijit Mondal Abhi Commented Jan 23, 2019 at 8:49
  • Why shouldn't moment("7:20", "H:mm") not work? – Oliver Commented Jan 23, 2019 at 8:50
  • @sunielkalwani 7:20 + 5:50 + 6:30 = 19:40 (Total Hours) – Abhijit Mondal Abhi Commented Jan 23, 2019 at 8:50
 |  Show 1 more comment

5 Answers 5

Reset to default 9

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>

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));

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"]));

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}`);

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())
发布评论

评论列表(0)

  1. 暂无评论