首页 > 解决方案 > 使用 javascript 构建营业时间

问题描述

我一直在尝试显示“目前在周一至周五开放”。& 将更改为“目前周六 - 周日关闭”。

我尝试通过谷歌搜索学习,但我无法实现:

window.onload = function status() {
    var date = new Date();
    console.log(date);
  //var day  = date.getDay();
    var hour = date.getHours();// 0 = 12am, 1 = 1am, ... 18 = 6pm\
    console.log(hour);

   // check if it's between 9am and 11pm
   if(hour > 12 ) {
      document.getElementById('example').innerHTML = "Currently opened on Monday - Friday.";
    } else if (hour < 23 ) {
      document.getElementById('example').innerHTML = "Currently closed on Saturday - Sunday.";
    } else {
      console.log('Today is not a weekend and hour is between 12 - 23')
    }
  };

setInterval(status, 1000);
console.log(status);

标签: javascripthtmldatetime

解决方案


您可以使用对象的getDay()方法Date来获取星期几,然后检查它是否是星期几,如果它打开了,那么你检查小时。

function status() {
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  //check if its sunday or saturday
  if (day == 0 || day == 6) {
    document.getElementById('example').innerHTML = "Currently closed on Saturday - Sunday.";
  // check if its between 9am and 11pm (inclusive)
  } else if (hour >= 9 && hour <= 23) {
    document.getElementById('example').innerHTML = "Currently opened on Monday - Friday.";
  } else {
    console.log('Today is not a weekend and hour is between 12 - 23')
  }
}

检查工作示例https://jsfiddle.net/93ut5jve/9/ 参考:


推荐阅读