繁体   English   中英

如何使用moment.js检查当前时间是否在两次之间

[英]How to check if the current time is between two times using momentjs

我试图做的是:

  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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM