gpt4 book ai didi

Javascript 检查时间是否在 8 :30am and 6:30pm 之间

转载 作者:行者123 更新时间:2023-12-03 09:44:10 25 4
gpt4 key购买 nike

好吧,正如标题所说。我在服务器上执行此操作,因此我使用一些 PHP 代码获取服务器的时间。问题在于它是一个没有精确的圆形小时值的时间范围。我应该使用嵌套的 if else 语句吗?

var serverTimestampMillis = <?php print time() * 1000 ?>;
var checkInterval = 1000;

var checkTime = function () {
serverTimestampMillis += checkInterval;

var now = new Date(serverTimestampMillis);

var timeDiv = document.getElementById('timeDiv');

var messageDiv = document.getElementById('messageDiv');

timeDiv.innerHTML = now.toString();


var dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ... 6 = Saturday

var hour = now.getHours(); // 0 = 12am, 1 = 1am, ... 18 = 6pm
var minutes = now.getMinutes();

// check if it's Monday to Thursday between 8:30am and 6:30pm
// this is where I don't know how to check 8:30
if (dayOfWeek > 0 && dayOfWeek < 5 && hour > 8 && hour < 18) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
else {
messageDiv.innerHTML = 'Sorry, we\'re closed!';
messageDiv.className='closed';
}
};

// check the time every 1000 milliseconds
setInterval(checkTime, checkInterval);
checkTime();

提前感谢您,很抱歉我是个菜鸟

最佳答案

使用辅助函数比较两个日期:

 function createDateTime(time) {
var splitted = time.split(':');
if (splitted.length != 2) return undefined;

var date = new Date();
date.setHours(parseInt(splitted[0], 10));
date.setMinutes(parseInt(splitted[1], 10));
date.setSeconds(0);
return date;
}

var startDate = createDateTime("8:30");
var endDate = createDateTime("17:30");
var now = new Date();
var isBetween = startDate <= now && now <= endDate;

console.log(isBetween);

JSFIDDLE.

关于Javascript 检查时间是否在 8 :30am and 6:30pm 之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31089944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com