首页 > 解决方案 > 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)
      }

标签: javascriptangularjswikitude

解决方案


您在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')
}

推荐阅读