我正在使用 jQuery 来显示不同的消息,具体取决于我工作的公司是否营业。由于该业务仅在 9.30 开始营业,我需要能够将其写入 jQuery,但到目前为止,我只能通过 google 搜索指定整点时间的内容。
var thehours = new Date().getHours();
var themessage;
var open = ('nu open');
var gesloten = ('nu gesloten');
if (thehours >= 9.30 && thehours < 18) {
themessage = open;
} else if (thehours >= 18 && thehours < 24) {
themessage = gesloten;
} else if (thehours >= 0 && thehours < 9.30) {
themessage = gesloten;
}
$('.bericht').append(themessage);
var thehours1 = new Date().getHours();
var themessage1;
var open1 = ('09.30 - 18.00');
var gesloten1 = ('18.00 - 09.30');
if (thehours1 >= 9.30 && thehours1 < 18) {
themessage1 = open1;
} else if (thehours1 >= 18 && thehours1 < 24) {
themessage1 = gesloten1;
} else if (thehours1 >= 0 && thehours1 < 9.30) {
themessage1 = gesloten1;
}
$('.bericht1').append(themessage1);
这是两条不同的消息,显示“现在开放/现在关闭”以及开放或关闭时间。
它有效,但似乎只表明我们在 10.00 和 18.00 之间开放,而不是 9.30 和 18.00,所以我想知道 9.30 的语法是否有误。
最佳答案
快速浏览 docs for getHours
会告诉你它返回
... integer number, between 0 and 23, representing the hour for the given date according to local time.
所以使用 9.30
将永远行不通(如果行得通,您将使用十进制数字来表示那个时间 - 难道不是 9.5
吗?!)
所以你需要几小时和分钟:
var date = new Date();
var hrs = date.getHours();
var mins = date.getMinutes();
if((hrs==9 && mins>30) || hrs >=10){
console.log("Its past 930am")
}
将此与您的其余逻辑放在一起给出:
function areWeOpen(){
var date = new Date();
var hrs = date.getHours();
var mins = date.getMinutes();
if(((hrs==9 && mins>30) || hrs >=10) && hrs<18){
return true;
}
return false;
}
console.log( areWeOpen() ? "We are open" : "We are closed");
简单!
关于javascript - JavaScript 中的时间/小时语法 - 如何处理不在整点的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43799768/