Thursday, 7 May 2009

Javascript to Change Message Based on the Time of Day

This Javascript function checks the time of day and returns Good Morning, if it's before midday, Good Afternoon, if it's between midday and 6pm and Good Evening if it's after 6pm.

function welcomeMessage()
{
var now = new Date();
var hours = now.getHours();
var msg;
if(hours<12)
msg = "Good Morning";
else if(hours<18)
msg = "Good Afternoon";
else
msg = "Good Evening";
return(msg);
}

As the date is taken from the client, so it doesn't matter where in the World the user is, they will get the message relevant to them.


Goodbye and

1 comment:

Helen said...

Thanks for this post, now I see how some sites manage to change the greeting depending on the time of day.

I will definitely use this piece of code. Thanks again for sharing.

Helen Neely