简体   繁体   中英

how to sum dates and times when the result is greater than 24 hours using moment.js

I'm having issues when trying to get the sum of times from an array when the result is over 24 hours. I'm using moment.js to get the duration and.reduce() to obtain the total of times, but when the result is over 24 hours: instead of showing 25 hours and 15 minutes, it is showing 1 hour and 15 minutes.

Here is my code:

const arrayOfTimes = ["02:24", "01:30", "20:00", "01:17", "00:45"] //25 hours and 56 minutes in total

const sum = arrayOfTimes.reduce(
  (time1, time2) => time1.add(moment.duration(time2)),
  moment.duration()
);

JSX

<h4 className="ml-3 text-light text-center">
   Total time worked:
   {Math.floor(sum.hours()) +
   " hours and " + sum.minutes() +
   " minutes"} //here is where it's showing 1 hour and 56 minutes instead of 25 hours and 56 minutes
</h4>

Does anyone know how to fix this, so it calculates and shows the right total of hours?

Could you use sum.days() * 24 + sum.hours() for the hours part?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM