我正在尝试在特定时间之间调用函数。在上午 6:00:00 到晚上 8:00:00 之间,应执行 myFunction()。否则应执行 otherFunction()。
if (new Date().getHours() > "6" && new Date().getHours() < "20") {
myFunction();
} else {
otherFunction();
}
上面有时有效..但我觉得它不准确...我也使用了 moment.js 和:
if (moment().format("h:mm:ss A") > "6:00:00 AM" && moment().format("h:mm:ss A") < "8:00:00 PM") {
我想我解决了这个问题:
var now = moment();
var amStart = moment('9:00 AM', 'h:mm A');
var amFinish = moment('10:00 PM', 'h:mm A');
if (now.isAfter(amStart) && now.isBefore(amFinish)) {
console.log('Success Function');
} else {
console.log('Failure Function')
}
最佳答案
getHours()
返回一个数字,而不是字符串,因此您应该与数字进行比较。
您需要使用>=
,而不是>
,因为当6:10
时,getHours()
> 将返回 6
,而 6 > 6
不为 true。
var hour = new Date().getHours();
if (hour >= 6 && hour < 20) {
myFunction();
} else {
otherFunction();
}
关于javascript - 如果当前时间大于且小于特定时间,如何调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39153941/