As children, we learned to greet our guests, family, and friends based on the time of day. While I don't need to reiterate those lessons now that we're all grown up 😊, it's important to extend these courtesies to our web page, ensuring it greets our visitors appropriately.
Note: ➡️ I have seen scripts written using Asp.Net and other server side languages, to do the same. However, be advised that the server time may not co-inside with the clients computer time. Therefore use a client side script like JavaScript for accuracy.
In our markup section, we have added a <label> to display the message. However, you may also use document.write() method for the same.
<html> <head> <title>Greeting Message using JavaScript</title> </head> <body> <label id="lblGreetings"></label> </body> <script> const myDate = new Date(); const hrs = myDate.getHours(); let greet; if (hrs < 12) greet = 'Good Morning'; else if (hrs >= 12 && hrs <= 17) greet = 'Good Afternoon'; else if (hrs >= 17 && hrs <= 24) greet = 'Good Evening'; document.getElementById('lblGreetings').innerHTML = '<b>' + greet + '</b> and welcome to Encodedna.com!'; </script> </html>
Output (in real time)
The JavaScript Date() method retrieves the current date and time from the user's computer. This method provides various set and get functions. Among these, the getHours() method is particularly useful, as it returns the hour of the day, ranging from 0 to 23.