Javascript .getHours()无法正常工作

时间:2016-05-18 10:30:30

标签: javascript

我使用以下javascript根据他们访问当天的时间动态向我的网站访问者显示消息。

var myDate = new Date(); 

/* hour is before noon */
if ( myDate.getHours() < 12 )  
{ 
    document.write("Good morning"); 
} 
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) 
{ 
    document.write("Good afternoon"); 
} 
else  /* the hour is after 5pm, so it is between 6pm and 2am */
if ( myDate.getHours() > 17 && myDate.getHours() <= 2 ) 
{ 
    document.write("Good evening"); 
} 
else  /* the hour is not between 0 and 24, so something is wrong */
{ 
    document.write("Hello"); 
} 

这是我在本网站上回答其他人的问题时找到的脚本。它工作得很好,但几个星期后,它没有显示出“晚安”的好消息。消息了。所以早上好'#39;和&#39;下午好&#39;他们应该按照自己的意愿工作,但是“晚上好”的那一刻。应显示消息,它只显示“Hello”,表示脚本出现问题。我试过重写它并改变时间,但我总是得到同样的错误。

有谁看到可能导致此问题的原因?谢谢!

3 个答案:

答案 0 :(得分:1)

您的问题是,getHours()的结果不会满足您的if条件。换句话说,getHours()的值不能是> 17<= 2

请尝试使用或(||)来满足您的评论要求:

if ( myDate.getHours() > 17 || myDate.getHours() <= 2 ) 

答案 1 :(得分:0)

长话短说,有人在您的代码中3之后删除了2。检查gitblame ./filename。实际代码应为:

 myDate.getHours() > 17 && myDate.getHours() <= 23

答案 2 :(得分:0)

var myDate = new Date(); 

/* hour is before noon */

console.log(myDate.getHours());
if ( myDate.getHours() >= 2 && myDate.getHours() < 12 )  
{ 
  console.log("Good morning"); 
} 
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) 
{ 
    console.log("Good afternoon"); 
} 
else if ( myDate.getHours() > 17 || myDate.getHours() <= 2  && myDate.getHours() >=0) 
{ 
    console.log("Good evening"); 
} 
else  /* the hour is not between 0 and 24, so something is wrong */
{ 
    console.log("Hello"); 
}