javascript - Javascript 日期/时间检查错误
问题描述
在我的应用程序中使用以下代码来显示 html 页面,具体取决于它是今天的日期以及一天中的哪个时间,例如早上、下午或晚上。目前是下午 2:53,代码只显示 am html 页面(这是第一个页面)。我尝试运行 console.log 命令,但控制台中什么也没有,这可能是因为维基百科。
获取日期的第一个功能正常工作,只是没有正确检查时间。
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')
}
推荐阅读
- raspberry-pi - 数码相框作为 RPI 4 的监视器
- javascript - 许多代码后我的服务器没有被加载
- c# - 我需要从异步任务中返回任何东西吗?
- doxygen - 在 doxygen 中查看源文件的问题
- javascript - 使用纯javascript提交表单后重定向
- r - 在 ggplot2 中,是否支持颜色名称中的空格?
- laravel - 如何将自定义变量从 ResetPasswordController 传递给重置刀片
- c# - OmniSharp.MSBuild.ProjectManager 试图更新未加载 csproj 的项目
- javascript - 更改三.js 线材运行时
- android - 如何从 GLSL 着色器中删除水平条纹伪影?