【问题标题】:How to check if the current time is between two times using momentjs如何使用momentjs检查当前时间是否在两次之间
【发布时间】:2019-06-02 12:56:38
【问题描述】:

我想做什么:

  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

上午 10:30 开门,晚上 11:30 关门

在这种情况下工作完美,因为时间在同一日期。

但是如果餐厅 23 小时营业呢:

上午 10:30 开门,上午 9:30 关门

那该如何处理呢?

【问题讨论】:

    标签: javascript time momentjs


    【解决方案1】:
    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);
    }
    

    【讨论】:

    • 不适用于以下情况:当前下午 5:41 关闭:晚上 7:00 和开放:晚上 11:49
    猜你喜欢
    • 1970-01-01
    • 2016-07-11
    • 2014-01-04
    • 1970-01-01
    • 2013-06-13
    • 2018-11-16
    • 2015-06-16
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多