营业时间:显示当前时间和假期

时间:2017-06-30 17:41:03

标签: javascript jquery

所以,我正在努力为特定网站添加营业时间。我发现这一点很有用,可以显示页面加载时的当前时间,并确定商店是否已关闭。但是,我想将页面加载时捕获的时间更改为活动时钟。我希望有人能帮忙。

页面加载时,会显示页面加载的时间。即在下午12:30访问网站,timeDiv显示12:30 PM。下午12:31,它仍然显示在下午12:30。

我想要的是一个活动时钟,因此在下午12:31显示12:31 PM并显示此后每个时间间隔的当前时间。

以下是原始笔的链接:https://codepen.io/zeinab92/pen/xwWGWM

var now = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var checkTime = function() {
  var today = weekday[now.getDay()];
  var timeDiv = document.getElementById('timeDiv');
  var dayOfWeek = now.getDay();
  var hour = now.getHours();
  var minutes = now.getMinutes();

  //add AM or PM
  var suffix = hour >= 12 ? "PM" : "AM";

  // add 0 to one digit minutes
  if (minutes < 10) {
    minutes = "0" + minutes; }

  if ((dayOfWeek === 1 || dayOfWeek === 2 || dayOfWeek === 3 || dayOfWeek === 4 || dayOfWeek === 5) && hour >= 9 && hour === 17 && minutes <=29) {
    hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
    timeDiv.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
    timeDiv.className = 'open';
  }

  else if ((dayOfWeek === 6) && hour >= 8 && hour === 15 && minutes <= 59) {
    hour = ((hour + 11) % 12 + 1);
    timeDiv.innerHTML = '<p id="hour">it\'s ' + today + ' ' + hour + ':' + minutes + suffix + '</p> <p id="stat">we\'re open!</p>';
    timeDiv.className = 'open';
  }

  else {
    if (hour === 0 || hour > 12) {
      hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
    }
    timeDiv.innerHTML = '<p id="hour">It\'s ' + today + ' ' + hour + ':' + minutes + suffix + '</p><p id="stat">we\'re closed!</>';
    timeDiv.className = 'closed';
  }
};

var currentDay = weekday[now.getDay()];
var currentDayID = "#" + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); /hightlights today in the view hours modal popup

setInterval(checkTime, 1000);
checkTime();

1 个答案:

答案 0 :(得分:0)

有一个非常流行的JavaScript库叫做momentjs,它很好地处理了很多日期/时间逻辑。我建议你从那里开始。

此代码的扩展方式与您需要投入假期的方式大致相同:

https://gist.github.com/jrhames/5200024

基本逻辑是在单独的自定义数组中跟踪您的假期,然后创建一个以日期作为参数的函数,并查找您的假期数组。