我一直试图显示“目前在星期一 - 星期五开放”。并将改为“目前在星期六 - 星期日休息。”
我试着通过谷歌搜索学习,但我无法实现:
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);
您可以使用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/参考:
这是一个简单的解决方案,可以帮助您指出正确的方向。
我认为您的代码存在的一个问题是它只捕获了一天中的小时,而不是一周中的某一天。
下面你可以在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);