我将尽我所能解释这一点。

我有DD / MM / YYYY格式的一系列独特日期,如下所示:

const sortDates = [
'14/04/2018',
'12/04/2018',
'10/04/2018',
]


然后我有一个带有以下信息的对象数组。

const bookings = [
  { bookingStart: '2018-04-14 00:30:00' },
  { bookingStart: '2018-04-14 00:42:00' },
  { bookingStart: '2018-04-14 13:35:00' },
  { bookingStart: '2018-04-12 12:30:00' },
];


而我想要达到的目标是每天每小时发现和分组一次数据。下面的例子:

const groupedData = [{
  date: '2018-04-14',
  period : {
     startTime: '00:00',
     endTime: '00:59',
     total: 2, //total bookings found 2018/04/14 00:00 -> 00:59
  },
  date: '2018-04-14',
  period : {
     startTime: '01:00',
     endTime: '01:59',
     total: 0,  //total bookings found 2018/04/14 01:00 -> 01:59
  },
  ...etc
}


但是我有点卡住。我当前的代码如下,并且不确定return语句应该如何:

const groupData = sortDates.map((date) => {
  for (let i = 0; i <= 23; i += 1) {
    const startTime = new Date(date);
    const endTime = new Date(date);
    startTime.setHours(i);
    startTime.setMinutes(0);
    startTime.setSeconds(0);
    startTime.setMilliseconds(0);
    endTime.setHours(i);
    endTime.setMinutes(59);
    endTime.setSeconds(0);
    endTime.setMilliseconds(0);
    bookings.map((booking) => {
      const dateTime = new Date(booking.bookingStart);
      if (startTime.getTime() >= dateTime.getTime()
      && dateTime.getTime() <= endTime.getTime()) {
        return {
          date: dateTime,
        };
      }
      return null;
    });
  }
  return null;
});


甚至不确定是最好的方法还是最快的方法,但是我将如何以我想要的格式返回?任何更快的选择?

最佳答案

使用moment.js的解决方案:

sortDates.forEach(date => {
  const dateMoment = moment(date, 'DD/MM/YYYY');
  const bookingsOnDate = bookings.filter(b =>
    dateMoment.isSame(b.bookingStart, 'day'),
  );

  const start = moment(dateMoment);
  const end = moment(dateMoment);

  for (let i = 0; i < 24; i++) {
    start.hour(i);
    start.minutes(0);
    end.hour(i);
    end.minutes(59);

    const foundCount = bookingsOnDate.filter(b => {
      const bookingMoment = moment(b.bookingStart);
      return (
        bookingMoment.isSameOrAfter(start) && bookingMoment.isSameOrBefore(end)
      );
    }).length;

    if (foundCount > 0) {
      groupedData.push({
        date: dateMoment.format('YYYY-MM-DD'),
        period: {
          startTime: start.format('HH:mm:ss'),
          endTime: end.format('HH:mm:ss'),
          total: foundCount,
        },
      });
    }
  }
});

10-07 14:32