我试图做的是:

  getOpenStatus = (restaurant: _Restaurant) => {
    const closeHour = moment(restaurant.close_at, "HH:mm A").hours();
    const closeMin = moment(restaurant.close_at, "HH:mm A").minutes();
    const openHour = moment(restaurant.open_at, "HH:mm A").hours();
    const openMin = moment(restaurant.open_at, "HH:mm A").minutes();
    const closeMoment = moment({ hours: closeHour, minutes: closeMin });
    const openMoment = moment({ hours: openHour, minutes: openMin });
    return moment().isAfter(openMoment) && moment().isBefore(closeMoment);
  }


假设当前时间是4:00 pm

上午10:30开放,下午11:30关闭

在这种情况下,由于时间是在同一日期,因此可以完美地工作。

但是,如果餐厅开放23小时该怎么办:

在上午10:30开放,在上午9:30关闭

那么如何处理呢?

最佳答案

getOpenStatus = (restaurant: _Restaurant) => {
    const closeHour = moment(restaurant.close_at, "HH:mm A").hours();
    const closeMin = moment(restaurant.close_at, "HH:mm A").minutes();
    const openHour = moment(restaurant.open_at, "HH:mm A").hours();
    const openMin = moment(restaurant.open_at, "HH:mm A").minutes();
    const closeMoment = moment({ hours: closeHour, minutes: closeMin });
    const openMoment = moment({ hours: openHour, minutes: openMin });

    if (closeMoment.isBefore(openMoment)) {
        if (moment().isAfter(closeMoment)) closeMoment.add(1, "days");
        else openMoment.subtract(1, "days");
    }

    return moment().isAfter(openMoment) && moment().isBefore(closeMoment);
}

关于javascript - 如何使用moment.js检查当前时间是否在两次之间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56415269/

10-10 09:16