As little kids, we were taught how to greet our guests, family and friends depending upon the time of the day. I need not repeat it here, because you all are grown up now. However, we need to make our web page understand these courtesies and greet ours visitors accordingly.
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, it advisable not to use a server side script. Instead, use a client side script 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> var myDate = new Date(); var hrs = myDate.getHours(); var 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
The JavaScript Date() method will return the current date and time of your user’s computer. The method offers many set and get methods. Out of many get methods, we will use the getHours() method, which will return hours between 0 and 23.