15.6 Greeting Users with Their Time of Day

NN 2, IE 3

15.6.1 Problem

You want your page to include a greeting pertinent to the user's part of the day, such as "Good morning" or "Good afternoon".

15.6.2 Solution

First, create a function that returns strings associated with each day part, as calculated by a fresh Date object:

function dayPart( ) {
    var oneDate = new Date( );
    var theHour = oneDate.getHours( );
    if (theHour < 12) {
        return "morning";
    } else if (theHour < 18) {
        return "afternoon";
    } else {
        return "evening";

To accommodate both scriptable and unscriptable browsers, be sure to encase the script statement inside HTML comment tags, and include the noscript element with the text to display for unscriptable browsers.

<script language="JavaScript" type="text/javascript">
document.write("Good " + dayPart( ) + " and welcome")
 to GiantCo.

15.6.3 Discussion

As the page loads, it creates an instance of a Date object. By omitting the parameter for the Date object constructor function, the current time and date are used to generate the object. A Date object instance is not a ticking clock, but rather a snapshot of the clock when the object was created. The accuracy of the time is strictly dependent upon the computer's internal clock setting.

A Date object has numerous functions for getting and setting components of the date, ranging from the millisecond to the year. The getHours( ) method used in the Solution returns a number between 0 and 23, corresponding to the 24-hour clock set to the user's local time. The dayPart( ) function simply divides the day into three portions, breaking at noon and 6 P.M. to supply day parts ranging through morning, afternoon, and evening.

15.6.4 See Also

Recipe 2.9 through Recipe 2.11 for information about working with the Date object.