javascript - 使用 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);
解决方案
您可以使用对象的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/ 参考:
推荐阅读
- javascript - 在 javascript 中添加具有不同来源的多个 iframe
- algorithm - 使用 O(k) 内存的 O(N) 运行时间的散列
- javascript - 检测二维空间中两个网格状物体的碰撞
- webpack - 三.js webpack的优势
- javascript - Javascript:在没有 JQuery 的选项卡列表中的类之间自定义切换
- javascript - 如何制作允许您进行文本/群聊的 chrome 扩展程序
- r - Rcpp:在构建 cppFunction() 时从现有 R 包中调用函数
- python - 检查 DataFrame 字符串值是否包含具有某些前缀的单词
- python - TypeError:只能将str(不是“list”)连接到str
- sql - SQL Server 错误:当子查询没有用 EXISTS 引入时,选择列表中只能指定一个表达式