如何使用moment.js和moment时区确定商店是打开还是关闭?

时间:2019-12-26 16:08:47

标签: javascript datetime momentjs moment-timezone

我在我的网站上使用momentjs,根据选定的特定商店位置的开放时间,关闭时间和时区来确定商店是否仍在营业。我制作的功能在某些时间范围内有效,但在某些时间范围内无效。

JS库

  

/moment.js
  /moment-timezone-with-data-10-year-range.js

我的示例代码

 function isOpen(openTime, closeTime, timezone){
  var  status = "closed";
  if(openTime != "24HR"){
    const  now = moment().tz(timezone);
    const  storeOpenTime = moment.tz(openTime, "h:mmA", timezone);
    const  storeCloseTime = moment.tz(closeTime, "h:mmA", timezone);
    /* const  storeOpenTime = moment.tz(Date.now(Date(openTime)), "h:mmA", timezone);
    const  storeCloseTime = moment.tz(Date.now(Date(closeTime)), "h:mmA", timezone);*/
    const  check = now.isBetween(storeOpenTime, storeCloseTime);
    if(check || check == true){
      status = "open";
    }
  }else{
    status = "open";
  }
  return status;
}

让我们假设马来西亚吉隆坡当前时间是11:34 PM,我运行以下代码

 isOpen("8:00AM", "12:20AM", "Asia/Kuala_Lumpur") 
 returned output = closed

以上代码的预期输出为open,但是如果马来西亚吉隆坡的当前时间为11:34 PM,则运行以下代码。

isOpen("8:00AM", "10:20PM", "Asia/Kuala_Lumpur")
returned output = closed

以上输出正确。

请问我如何使用国家时区使用momentjs检查打开和关闭之间的时间是否过去了?

1 个答案:

答案 0 :(得分:1)

以下是您的代码已更正并注释:

function isOpen(openTime, closeTime, timezone) {

  // handle special case
  if (openTime === "24HR") {
    return "open";
  }

  // get the current date and time in the given time zone
  const now = moment.tz(timezone);

  // Get the exact open and close times on that date in the given time zone
  // See https://github.com/moment/moment-timezone/issues/119
  const date = now.format("YYYY-MM-DD");
  const storeOpenTime = moment.tz(date + ' ' + openTime, "YYYY-MM-DD h:mmA", timezone);
  const storeCloseTime = moment.tz(date + ' ' + closeTime, "YYYY-MM-DD h:mmA", timezone);

  let check;
  if (storeCloseTime.isBefore(storeOpenTime)) {
    // Handle ranges that span over midnight
    check = now.isAfter(storeOpenTime) || now.isBefore(storeCloseTime);
  } else {
    // Normal range check using an inclusive start time and exclusive end time
    check = now.isBetween(storeOpenTime, storeCloseTime, null, '[)');
  }

  return check ? "open" : "closed";
}

// Testing
const zone = "Asia/Kuala_Lumpur";
console.log("now", moment.tz(zone).format("h:mmA"));
console.log("24HR", isOpen("24HR", undefined, zone));
console.log("2:00AM-8:00AM", isOpen("2:00AM", "8:00AM", zone));
console.log("8:00AM-2:00PM", isOpen("8:00AM", "2:00PM", zone));
console.log("2:00PM-8:00PM", isOpen("2:00PM", "8:00PM", zone));
console.log("8:00PM-2:00AM", isOpen("8:00PM", "2:00AM", zone));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.27/moment-timezone-with-data-10-year-range.min.js"></script>

您遇到的主要问题是必须解决issue #119中描述的错误,即在特定时区中仅解析时间时,Moment错误地应用了UTC日期而不是tz-特定的本地日期。

其次,您还需要通过检查打开/关闭时刻是否乱序来处理跨越午夜的时间范围的情况。如果是这样,则需要以不同的方式进行比较-通过检查当前时间是在打开之后还是关闭之前。