2

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

var arr[0]=
[
 {
   "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",
 } 
]

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

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

4

2 回答 2

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>

于 2018-05-08T03:32:39.460 回答
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
于 2018-05-08T02:39:08.807 回答