Создание рабочих часов с помощью JavaScript - PullRequest
0 голосов
/ 14 сентября 2018

Я пытался отобразить «В настоящее время открыт с понедельника по пятницу». & собирается изменить на «В настоящее время закрыто в субботу - воскресенье».

Я пытаюсь научиться гуглить, но не смог достичь:

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);

Ответы [ 2 ]

0 голосов
/ 14 сентября 2018

вы можете использовать метод 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/ ссылки:

0 голосов
/ 14 сентября 2018

Вот простое решение, которое может помочь вам указать правильное направление.

Я думаю, что одна из проблем с вашим кодом состоит в том, что он захватывает только час дня, а не день недели.

Ниже вы можете установить свои дни и часы работы в объекте open, но если у вас будет другое время открытия в разные дни в будущем, вам нужно будет определить объект open по-разному и будет иметьизменить как работает функция getStatus

// set up the interval so that the time can be started and stopped as needed
    var interval;

// set the days and times when open (this could be set up differently, for example it could be a range instead)
    var open = {
        days: [1, 2, 3, 4, 5],
        hours: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
    }

// given a date, return a message determining if open
    var getStatus = function(currentDate){
        var hour = currentDate.getHours();
        var day = currentDate.getDay();
        var nowIsOpenDay = open.days.indexOf(day) > -1;
        var nowIsOpenHour = open.hours.indexOf(hour) > -1;

        var message = (nowIsOpenDay && nowIsOpenHour) ? 'Currently opened' : 'Currently closed';

        return {
            'message': message,
            'dateInfo': {
                'hour': hour,
                'day': day,
                'nowIsOpenDay': nowIsOpenDay,
                'nowIsOpenHour': nowIsOpenHour
            }
        }

    }

// run the timer and get the current status
    var startInterval = function(updateInterval){
        updateInterval = (typeof updateInterval === 'undefined') ? 1000 : updateInterval;
        interval = setInterval(function(){
            var currentStatus = getStatus(new Date());
            console.log(currentStatus.message)
            console.log(currentStatus.dateInfo.hour, currentStatus.dateInfo.day)
        }, updateInterval);
    }

// optionall stop the interval
    var stopInterval = function(){
        clearInterval(interval);
    }

// start
    startInterval(2000);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...