计算对象中属性的总持续时间

时间:2018-05-08 02:34:51

标签: javascript angularjs reduce pure-function

我在数组[0]中有以下对象:

pv

end_datatime格式为yyyymmddMhhmmss(前4位数字为年份,后跟月份,天数,分隔符“M”,小时,分钟和秒。

我想计算所有活动的总持续时间? (总共11小时,即2小时的睡眠+ 4小时的早餐+ 1小时的课程+ 4小时的滑雪)

2 个答案:

答案 0 :(得分:1)

您需要一个累加器来跟踪到目前为止的时间。我假设数字指的是分钟或其他东西。如果它实际上是时间(如在1700 = 5PM),那么你显然需要做更多的逻辑(因为事件可以从1159开始并在0100结束,在这种情况下,startTime - endTime将不起作用) ,但是从你的尝试来看,你似乎只是在寻找两个数字之间的差异。这是我得到的:

arr = [
{
   "startTime": "1300",
    "endTime": "1700",
    "eventName": "Tea" 
 },
 {
    "startTime": "0800",
    "endTime": "1200", 
    "eventName": "Breakfast" 
 },
 {
   "startTime": "1300",
    "endTime": "1400",
    "eventName": "Lesson" 
 },
 {
    "startTime": "1300",
    "endTime": "1700",
    "eventName": "Ski"
 } 
]

arr.reduce((acc, val) => {
  return acc + (parseInt(val.endTime) - parseInt(val.startTime))
}, 0)

// returns 1300

答案 1 :(得分:1)

这是一种可能的实施方式,考虑到跨越多天的时间:



const input = [{
    "startTime": "1300",
    "endTime": "1700",
    "eventName": "Sleep",
    "end_datetime": "20180510M0100",
    "start_datetime": "20180509M2300",
  },
  {
    "startTime": "0800",
    "endTime": "1200",
    "eventName": "Breakfast",
    "end_datetime": "20180507M1200",
    "start_datetime": "20180507M0800",
  },
  {
    "startTime": "1300",
    "endTime": "1400",
    "eventName": "Lesson",
    "end_datetime": "20180507M1400",
    "start_datetime": "20180507M1300",
  },
  {
    "startTime": "1300",
    "endTime": "1700",
    "eventName": "Ski",
    "end_datetime": "20180511M170000",
    "start_datetime": "20180511M130000",
  }
];

function getDiff(datestr1, datestr2) {
  const m1 = moment(datestr1, 'YYYYMMDD*hhmm');
  const m2 = moment(datestr2, 'YYYYMMDD*hhmm');
  const minuteDifference = m2.diff(m1, 'minutes');
  return minuteDifference;
}
const totalMinutes = input.reduce(
  (accum, {
    end_datetime,
    start_datetime
  }) => accum + getDiff(start_datetime, end_datetime),
  0
);
const totalHours = totalMinutes / 60;
console.log(totalMinutes + ' minutes = ' + totalHours + ' hours');

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
&#13;
&#13;
&#13;