首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用momentjs检查当前时间是否在两个时间之间

如何使用momentjs检查当前时间是否在两个时间之间
EN

Stack Overflow用户
提问于 2019-06-02 20:56:39
回答 1查看 35关注 0票数 1

我想要做的是:

代码语言:javascript
复制
  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关闭

那么该如何处理呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-02 22:28:30

代码语言:javascript
复制
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);
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56415269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档