首页 > 解决方案 > 如何使用moment.js对结果大于24小时的日期和时间求和

问题描述

当结果超过 24 小时时,我在尝试从数组中获取时间总和时遇到问题。我正在使用 moment.js 来获取持续时间,并使用 .reduce() 来获取总时间,但是当结果超过 24 小时时:它不是显示 25 小时 15 分钟,而是显示 1 小时 15 分钟。

这是我的代码:

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>

有谁知道如何解决这个问题,所以它计算并显示正确的总小时数?

标签: javascriptreactjsmomentjs

解决方案


你可以使用sum.days() * 24 + sum.hours()小时部分吗?


推荐阅读