Senne Vandenputte
Senne Vandenputte

Reputation: 539

Javascript .getHours() not working correctly

I use the following javascript to dynamically show a message to my website visitors based on the time of the day they are visiting.

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"); 
} 

This is a script I found in an answer on someone else's question on this site. It was working great but since a few weeks, it's not showing the 'Good evening' message anymore. So the 'Good morning' and 'Good afternoon' are working as they should, but the moment the 'Good evening' message should be shown, it just shows 'Hello', indicating something is wrong with the script. I have tried rewriting it and changing the times but I always get the same error.

Does anyone see what could cause this problem? Thanks!

Upvotes: 0

Views: 653

Answers (3)

Nazır Dogan
Nazır Dogan

Reputation: 1588

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"); 
} 

Upvotes: 0

sapy
sapy

Reputation: 9592

Long story short , somebody deleted the 3 after 2 in your code . Check gitblame ./filename . Actual code should be:

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

Upvotes: 0

Matt Way
Matt Way

Reputation: 33199

Your problem is that no result for getHours() will satisfy your if condition. In other words, no value for getHours() can be > 17 and <= 2.

Try instead using or (||) to meet your comment requirements:

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

Upvotes: 1

Related Questions