在我的应用程序中使用以下代码来显示 html 页面,具体取决于今天的日期以及一天中的哪个时间,例如早上、下午或晚上。目前是下午 2:53,代码仅显示 am html 页面(这是第一个页面)。我尝试运行 console.log 命令,但控制台中没有任何内容,这可能是由于 wikiitude 的原因。
获取日期的第一个功能工作正常,只是没有正确检查时间。
var inputDate = new Date("5/17/2018");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
var hour = new Date().getHours();
console.log("hour is: " + hour);
// between 12 PM and 7 AM respectively
if(hour => 7 && hour < 12) {
//morning (Always running code here no matter what time of day)
}
else if(hour >= 12 && hour <= 18) {
//afternoon
}
else {
//evening or before 7
}
}
else{
//not today (works if date is not today)
}
最佳答案
您的 if
语句中有拼写错误:=>
应该是 >=
var inputDate = new Date("5/17/2018");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if (inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
var hour = new Date().getHours();
console.log("hour is: " + hour);
// between 12 PM and 7 AM respectively
if (hour >= 7 && hour < 12) {
//morning (Always displaying code here)
alert('morning')
}
else if (hour >= 12 && hour <= 18) {
//afternoon
alert('afternoon')
}
else {
//evening or before 7
alert('evening')
}
}
else {
//not today
alert('not today')
}
关于JavaScript 日期/时间检查错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50393297/