Hour based greeting

The scripting function shown below returns a greeting message based on the current hour. So if you have ever wondered: how do you display "Good morning", "Good afternoon", "Good evening", or "Good night"? The answer is not that you manually change the greeting based on the hour of the day; as that won't be practical. See the script below for an answer. It uses a function called GetHourBasedGreeting () that returns the greeting based on the hour (obtained by using the getHours () method).

The output of the script:

Scripting code

Step 1: place the following code in the head section (between <head> and </head>) of your web document.

<script language="javascript">
function GetHourBasedGreeting () {
var dateObj = new Date ();
var currHour = dateObj.getHours (); // gets current hour: 0 - 23
var greeting;
// is hour less than 12?
if (currHour < 12) {
greeting = "Good morning!";
// Or is hour between 12 and 17?
else if (currHour > 11 && currHour < 17) {
greeting = "Good afternoon!";
// Or is hour between 17 and 20?
else if (currHour > 16 && currHour < 20) {
greeting = "Good evening!";
// Or is hour between 20 and 23?
else if (currHour > 19 && currHour <= 23) {
greeting = "Good night!";
return greeting;

In the function above, we start by creating a date object called dateObj. Next, we use the getHours () method with the dateObj to read the current hour. Note getHours () returns a value 0 - 23. Next, we have couple of conditional statements to check if the hour is between certain numerical values. For instance, if currHour is less than 12 (in other words 0 - 11), we use the greeting: "Good Morning."

Step 2: Call the GetHourBasedGreeting () function from your web page:

<script language="javascript" type="text/javascript">
document.write (GetHourBasedGreeting());

In step 2, we call the GetHourBasedGreeting () function to return to us the greeting based on the current hour.