Copyright ©1996, Que Corporation. All rights reserved. No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews. Making copies of any part of this book for any purpose other than your own personal use is a violation of United States copyright laws. For information, address Que Corporation, 201 West 103rd Street, Indianapolis, IN 46290 or at support@mcp .com.

Notice: This material is excerpted from JavaScript By Example, ISBN: 0-7897-0813-2. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.

Chapter 12 - Date Methods

In this chapter, you learn how to use the methods associated with date objects. Associated to math and string methods, date methods add another dimension to your scripting ability and flexibility. The similarities among the form and function of the three types of methods quickly become apparent. Combined with your knowledge of math and string methods, the knowledge of date methods that you gain in this chapter will allow you to perform calculations on dates and display them in an aesthetically pleasing manner.

Date Objects

Date methods are used to manipulate date objects, JavaScript's encapsulation of an interface to the user's system clock (the clock running on the user's computer). With date objects, you can

Before you can manipulate a date object, you must create one with the new keyword. You can create date objects in three ways:

dateObjectVariable = new Date("month day, year hours:minutes:seconds")

birthday = new Date("September 7, 1970 13:00:00")

In JavaScript, time is stored in military or 24-hour format, where 1 p.m. is 13:00, 2 p.m. is 14:00, and so on.

dateObjectVariable = new Date(year, month, day, hours, minutes, seconds)

birthday = new Date(9, 7, 70, 13, 0, 0)

In all cases, dateObjectVariable is the variable that becomes your new date object.

Whether you're creating a date from a string or from integers, you can omit the hours, minutes, or seconds. If you do, those values are set to zero. So the preceding examples,

birthday = new Date("September 7, 1970")

birthday = new Date(9, 7, 70)

are both valid, and would set the time to 0:00:00 (midnight).

Date Methods

There are three broad categories of date methods: set, get, and conversion. The first two categories are easy to find because each begins with set or get followed by the remainder of the method name. They're also easy to understand, as they either "set" (change) the date variable or "get" (receive) the date into a variable.

The conversion methods, however, are slightly different and less intuitive. Conversion methods include parse(), toGMTString(), toLocaleString(), and UTC(). parse() and UTC() convert a given date object into the number of milliseconds since January 1, 1970, 00:00:00. ToGMTString() and toLocaleString() convert a given number of milliseconds into a date, again since January 1, 1970 00:00:00.

getDate()

The getDate() method returns the day of the month for the date object that you give the method. Therefore, the value that getDate() returns is a number between 1 and 31. The method's syntax should look familiar:

dateVariable.getDate()

The following code section assigns the variable dayNumber a value of 14:

vDay = new Date("February 14, 1996 12:00:01")

dayNumber = vDay.getDate()

getDay()

The getDay() method returns the day of the week for the date object that you give the method. You might expect that this method returns a string value, such as Sunday or Monday. However, the return value is instead a number, beginning at zero, corresponding to the day of the week, as follows:

Return Day
Value Represented
0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday

The syntax for the getDay() method is as follows:

dateVariable.getDate()

The following example code section assigns the variable dayOfWeek a value of 3 (because February 14, 1996, fell on a Wednesday that year):

vDay = new Date("February 14, 1996 12:00:01");

dayOfWeek = vDay.getDay();

Although a number representation is useful for calculations on the time period between dates, the representation that most people usually want is the actual day of the week. Converting the getDay() value to a text string of the name of the day is quite simple. In fact, the companion CD provides the file CONVDATE.HTM, which contains the functions convertDay() and convertDayShort(), which perform this conversion:

document.writeln(convertDay(dayOfWeek));

document.writeln(convertDayShort(dayOfWeek));

A single call to convertDay() and convertDayShort() in the following examples yields Wednesday and Wed, respectively, as listing 12.1 shows.

Listing 12.1

function convertDay(dayValue) {

// This function takes a dayValue (usually returned from the

// getDay() method) and converts that numeral into the string

// text for the day of the week.

strDay.length = 7; // necessary to 'allocate' array space

strDay[0] = "Sunday";

strDay[1] = "Monday";

strDay[2] = "Tuesday";

strDay[3] = "Wednesday";

strDay[4] = "Thursday";

strDay[5] = "Friday";

strDay[6] = "Saturday";

return strDay[dayValue];

}

function convertDayShort(dayValue) {

// This function takes a dayValue (usually returned from the

// getDay() method) and converts that numeral into the string

// text for abbreviation of the day of the week.

strDay.length = 7; // necessary to 'allocate' array space

strDay[0] = "Sun";

strDay[1] = "Mon";

strDay[2] = "Tue";

strDay[3] = "Wed";

strDay[4] = "Thr";

strDay[5] = "Fri";

strDay[6] = "Sat";

return strDay[dayValue];

}

The code segment in listing 12.2 demonstrates the use of these functions and their return values. (Notice that the program also incorporates string methods introduced in Chapter 11, "String Methods.")

Listing 12.2

document.writeln("Here is day 0 Long: " + convertDay(0).fontcolor("red") + "<br>");

document.writeln("Here is day 1 Long: " + convertDay(1) + "<br>");

document.writeln("Here is day 6 Long: " + convertDay(6).fontcolor("blue") + "<br><hr>");

document.writeln("Here is day 2 Short: " + convertDayShort(2).fontcolor("green") + "<br>");

document.writeln("Here is day 4 Short: " + convertDayShort(4).fontcolor("yellow") + "<br>");

document.writeln("Here is day 3 Short: " + convertDayShort(3).fontcolor("purple") + "<br><hr>");

document.writeln("<br>");

Figure 12.1 shows the resulting output.

Figure 12.1

This example demonstrates the combined use of date and string methods.

You also could convert from the day string to the numerical representation, as listing 12.3 shows.

Listing 12.3

function convertToDay(dayString) {

// This function converts a dayString (the text of the day of

// the week) into the corresponding numeric code of the day of

// the week.

searchValue = dayString.substring(0,3).toLowerCase();

if(searchValue == "sun")

return 0;

if(searchValue == "mon")

return 1;

if(searchValue == "tue")

return 2;

if(searchValue == "wed")

return 3;

if(searchValue == "thu")

return 4;

if(searchValue == "fri")

return 5;

if(searchValue == "sat")

return 6;

}

Notice that the first line of this function creates a substring (searchValue) consisting of the first three characters of dayString (as well as converts the substring to lowercase). This substring is then used to determine the day of the week, allowing this function to work for both full day names (Wednesday) and three-character "short" names (Thu). Converting the substring to lowercase makes it easier to compare strings, as you don't need to concern yourself with capitalization.

getHours()

The getHours() method returns the hour of the day for the date object that you give the method. The value that getHours() returns is a number between 0 and 23, based on a 24-hour clock system. The method's syntax is as follows:

dateVariable.getHours()

The following code section assigns a value of 12 to the variable hourOfDay:

vDay = new Date("February 14, 1996 12:00:01");

hourOfDay = vDay.getHours();

getMinutes()

The getMinutes() method returns the minutes from the time of day for the date object that you give the method. The value that getMinutes() returns is a number between 0 and 59. The method's syntax is as follows:

dateVariable.getMinutes()

The following code section assigns a value of zero to the variable minutes:

vDay = new Date("February 14, 1996 12:00:01");

minutes = vDay.getMinutes();

getMonth()

The getMonth() method returns the month of the year for the date object that you give the method. The value that getMonth() returns is a number between 0 and 11, with 0 representing January and 11 representing December. The method's syntax is as follows:

dateVariable.getMonth()

The following code segment assigns a value of 1 to the variable month:

vDay = new Date("February 14, 1996 12:00:01");

month = vDay.getMonth();

The file convdate.htm on the companion CD includes two functions, convertMonth() and convertMonthShort(), that convert getMonth()'s return value to a long or short textual version, respectively (see listing 12.4).

Listing 12.4

function convertMonth(monthValue) {

// This function converts a monthValue (usually returned from

// the getMonth() method) numeral into the string text for the

// month of the year.

strMonth.length = 12; // necessary to 'allocate' array space.

strMonth[0] = "January";

strMonth[1] = "February";

strMonth[2] = "March";

strMonth[3] = "April";

strMonth[4] = "May";

strMonth[5] = "June";

strMonth[6] = "July";

strMonth[7] = "August";

strMonth[8] = "September";

strMonth[9] = "October";

strMonth[10] = "November";

strMonth[11] = "December";

return strMonth[monthValue];

}

function convertMonthShort(monthValue) {

// This function converts a monthValue (usually returned from

// the getMonth() method) into the string text for the

// abbreviation of the month of the year.

strMonth.length = 12; // necessary to 'allocate' array space.

strMonth[0] = "Jan";

strMonth[1] = "Feb";

strMonth[2] = "Mar";

strMonth[3] = "Apr";

strMonth[4] = "May";

strMonth[5] = "June";

strMonth[6] = "July";

strMonth[7] = "Aug";

strMonth[8] = "Sep";

strMonth[9] = "Oct";

strMonth[10] = "Nov";

strMonth[11] = "Dec";

return strMonth[monthValue];

}

Using the two functions in listing 12.5 yields the output shown in figure 12.2.

Listing 12.5

document.writeln("Month 0 (long format): " + convertMonth(0) + "<br>");

document.writeln("Month 11 (long format): " + convertMonth(11) + "<br>");

document.writeln("Month 6 (long format): " + convertMonth(6) + "<br><hr>");

document.writeln("Month 3 (short format): " + convertMonthShort(3) + "<br>");

document.writeln("Month 7 (short format): " + convertMonthShort(7) + "<br>");

document.writeln("Month 9 (short format): " + convertMonthShort(9) + "<br><hr>");

Figure 12.2

This example demonstrates the use of the convertMonth() and convertMonthShort() functions found in the convdate.htm file.

getSeconds()

The getSeconds() method returns the seconds from the time of day for the date object that you give the method. The value that the method returns is a number between 0 and 59. The syntax for getSeconds() is as follows:

dateVariable.getSeconds()

The following code section assigns a value of 1 to the variable seconds:

vDay = new Date("February 14, 1996 12:00:01")

seconds = vDay.getSeconds()

getTime()

The getTime() method returns a numeric value corresponding to the number of milliseconds that have elapsed since January 1, 1970 00:00:00. This number isn't very useful or intuitive, as the example later in this section indicates.

As with other areas of computing, however, such less-intuitive values often possess great computational power. By using two getTime() statements and subtracting their results, for example, you can get the exact time between two events. You then need only to convert the milliseconds into a more readable format. This is much less a hassle than having to count days and remember how many days are in each month and whether the time frame includes any leap years.

As with the getYear() method discussed later in this chapter, getTime() now supports dates only from 1/1/1970 to 12/31/1999. Passing any other dates is an illegal operation that will crash the browser.

The following example demonstrates the use of getTime()'s format:

vDay = new Date("February 14, 1996 12:00:01");

document.writeln(vDay.getTime());

The rather obscure return value for this example (which, of course, will vary depending on the exact millisecond that you execute it) is as follows:

824317201000

getTimeZoneOffset()

Greenwich Mean Time (GMT), also called Coordinated Universal Time (or UTC), is the global standard for time. GMT is the current time at the Prime Meridian (or longitude 0[dg]), which runs through the Royal Observatory just outside Greenwich, England (hence the name). Starting from the Prime Meridian, GMT establishes time zones around the world based on 24 one-hour segments.

Establishing the time based on a standard instead of using local time zones is often desirable or even necessary. For example, if you sell merchandise on your Web page, you want to know the precise times when customers have placed their orders. By keeping track of these times, you can ensure the promptness, priority, and efficiency of your service. Suppose, however, that your Web page's captured time is based on the user's local time zone. With orders coming in from all over the world, you couldn't accurately distinguish and sort the placed orders according to the time of entry, because the times wouldn't be based on a standard time zone format. An order placed simultaneously from California and New York would register the Californian order as entered before the one from New York. Your Web page needs to use a base time to record the actual moment at which each customer has placed an order.

Although you could use your local time zone as the standard time for your Web page, you would then have to convert the user's local time to GMT, and then convert from GMT to your local time. To avoid having to perform this double conversion, Internet applications often simply adopt the GMT standard.

The GetTimeZoneOffset() method provides a way to set times to a standard zone format. This method doesn't actually do the conversion—instead, it returns the difference (in minutes) between the user's local time and GMT.

Because all other date methods measure time in milliseconds, you need to remember to convert the value returned by GetTimeZoneOffset() to milliseconds before you use it for time computations—either by multiplying the value by 60,000, or by using a function such as SetStandardTime(), which you can find on the companion CD in the file convdate.htm:

function setStandardTime(zoneDay) {

offset = zoneDay.getTimezoneOffset(); // Get time zone offset

offset *= 60000; // convert to milliseconds

offset += zoneDay.getTime(); // combine offset and current day

// in numeric format

zoneDay.setTime(offset); // set zoneDay to date now in

// standardized time

return zoneDay;

}

The following code calls the SetStandardTime() function:

vDay = new Date("February 14, 1996 12:00:01");

vDay2 = new Date(vDay);

standardDay = setStandardTime(vDay);

strDay1 = vDay2.toString();

strDay2 = standardDay.toString();

document.writeln("Standardized time for<br>");

document.writeln(strDay1.fontcolor('blue') + "<br>");

document.writeln(" is <br>");

document.writeln(strDay2.fontcolor('red') + "<hr>");

Note that this example requires two variables for the original date. Two "copies" are required because JavaScript transfers the variable's address, not its contents, to a function (in the programming world, this is called passing by reference). This means that any manipulation done on a variable (such as calling an object's method to modify the object) will change the variable—even outside the function. Because you want to send the same date value to two different functions (the first of which actually changes the object), you use new to make a second copy.

When this code calls SetStandardTime(), it produces the results shown in figure 12.3.

Figure 12.3

The example program displays this output after converting the date for Valentine's Day 1996 from Eastern Standard Time to GMT.

Although JavaScript date objects output strings and take strings as input, they aren't really strings. As a result, you can't use string manipulation methods (such as fontcolor()) on them directly. That's why (in the previous example) temporary string copies of the dates were made by using the toString() method (discussed later in the chapter).

getYear()

The getYear() method returns the year from the date object that you give the method. The value that getYear() returns is a number computed by subtracting 1900 from the year in the date object.

As with getTime(), only dates ranging from 1970 to 1999 are valid entries. A date outside that range causes Netscape 2.0 to perform an illegal operation and terminate itself (see fig. 12.4). A page that does that to its visitors won't be frequented often.

Obviously, this limited range will have to change by the year 2000; otherwise, major problems will arise. Look for newer Web browser releases to incorporate changes to address this problem.

Figure 12.4

To avoid displaying this dialog box to your visitors while manipulating date methods, you must carefully ensure that you use proper coding.

getYear()'s syntax is as follows:

dateVariable.getYear()

The following code section assigns a value of 96 to the variable Year:

vDay = new Date("February 14, 1996 12:00:01");

Year = vDay.getYear();

parse()

The numeric value that the parse() method returns represents the number-of-milliseconds difference between the given date and January 1, 1970. The method calculates the date by using the local time zone, not a standard time such as GMT.

The parse() method assumes that the date object is in the local time and bases its computations accordingly. If the date object is in GMT time, the result returned by parse() will be off by the difference between local time and GMT time. For example, in the Central Time Zone of the United States, parse() would return a value that's 6 hours ahead of the actual local time.

Notice the difference in the syntax that this method uses:

Date.parse(dateVariable)

This difference arises from parse() being a static method of Date, not a method of a date object that has been created.

The following example uses parse():

vDay = new Date("February 14, 1996 12:00:01");

document.writeln(Date.parse(vDay));

This example returns the following numeric value:

824317201000

The numeric value from parse() is useful when combined with the setTime() method (described later in this chapter), which returns the numeric value to a date.

setDate()

The setDate() method is the opposite of the getDate() method. It allows you to change the day of the month for a date object, and has the following syntax:

dateVariable.setDate(dayNumber)

dayNumber is any valid numeric integer ranging from 1 to 31 representing the day of the month.

The following code section is the same as the one shown for the getDate() method, except that after extracting dayNumber, this program changes it and places it back into vDay:

vDay = new Date("February 14, 1996 12:00:01");

dayNumber = vDay.getDate();

document.writeln("Date before change is " + vDay + "<br>");

dayNumber = 6;

vDay.setDate(dayNumber);

document.writeln("Date is now changed to " + vDay + "<br>");

The program produces this output:

Date before change is Wed Feb 14 12:00:01 1996

Date is now changed to Tue Feb 06 12:00:01 1996

Note, however, the effect of changing the date to an unacceptable number. If you set dayNumber = 6 to dayNumber = 31, your output is as follows:

Date before change is Wed Feb 14 12:00:01 1996

Date is now changed to Sat Mar 02 12:00:01 1996

The program automatically updates the day of the week in both examples, but in the second example, the program also updates the month. Although you use and treat dates as strings, the dates are actually numeric codes presented in a more understandable form. At the same time, however, dates aren't strictly numbers, because you can't add or subtract them without first changing them by using a method such as parse() or UTC().

setHours()

The complement to getHours(), setHours() lets you change the hours for a date object. It has the following syntax:

dateVariable.setHours(hoursOfDay)

hoursOfDay is any valid numeric integer ranging from 0 to 23, representing the 24 hours of the day.

The following code section is the same as the one shown for the getHours() method, except that after extracting hoursOfDay, the program changes it and puts it back into vDay:

vDay = new Date("February 14, 1996 12:00:01");

dayNumber = vDay.getHours();

document.writeln("Hours before change is " + vDay + "<br>");

hoursOfDay = 6;

vDay.setHours(hoursOfDay);

document.writeln("Hours is now changed to " + vDay + "<br>");

This program's output is as follows:

Hours before change is Wed Feb 14 12:00:01 1996

Hours is now changed to Wed Feb 14 06:00:01 1996

Note, however, the effect of changing the hours to an unacceptable number. If you set hoursOfDay = 6 to hoursOfDay = 31, you get the following results:

Hours before change is Wed Feb 14 12:00:01 1996

Hours is now changed to Thu Feb 15 07:00:01 1996

Notice that the second example automatically updates the day of the month from 14 to 15.

setMinutes()

You already have seen how to extract the minutes from a date object. The setMinutes() method allows you to change the minutes for a date object. It has the following syntax:

dateVariable.setMinutes(minutes)

minutes is any valid numeric integer ranging from 0 to 59, representing the minutes in the hour.

The following code section is the same as the example for the getMinutes() method, except after extracting minutes, this program changes it and puts it back into vDay:

vDay = new Date("February 14, 1996 12:00:01")

minutes = vDay.getMinutes()

document.writeln("Minutes before change is " + vDay + "<br>")

minutes = 6

vDay.setMinutes(minutes)

document.writeln("Minutes is now changed to " + vDay + "<br>")

The program's output is as follows:

Minutes before change is Wed Feb 14 12:00:01 1996

Minutes is now changed to Wed Feb 14 12:06:01 1996

Note, however, the effect of changing the minutes to an unacceptable number. If you set minutes = 6 to minutes = 74, you get the following results:

Minutes before change is Wed Feb 14 12:00:01 1996

Minutes is now changed to Wed Feb 14 13:14:01 1996

Notice that the second example automatically updates the hour from 12 to 13.

setMonth()

You've seen how to extract the month from a date object. The setMonth() method reverses the process, allowing you to set or change the month in a date object. Its syntax is

dateVariable.setMonth(month)

where month is any valid numeric integer ranging from 0 to 11, representing the month of the year for the date (0 equals January, 11 equals December).

The following code section is the same one you saw for the getMonth() method, except after extracting month, the program changes it and puts it back into vDay:

vDay = new Date("February 14, 1996 12:00:01");

month = vDay.getMonth();

document.writeln("Month before change is " + vDay + "<br>");

month = 6;

vDay.setMonth(month);

document.writeln("Month is now changed to " + vDay + "<br>");

This program's output is as follows:

Month before change is Wed Feb 14 12:00:01 1996

Month is now changed to Sun Jul 14 13:00:01 1996

You expect the change from Feb to Jul, but why did the hours change from 12 to 13? Daylight savings time.

Note, however, the effect of changing the month to an unacceptable number. If you set month = 6 to month = 14, you get the following results:

Month before change is Wed Feb 14 12:00:01 1996

Month is now changed to Fri Mar 14 12:00:01 1997

Notice that the program automatically updates the month, changes the year to 1997, and keeps the hours at 12 because the two months fall "outside" daylight savings time.

setSeconds()

You've already seen how to extract the seconds from a date object. The setSeconds() method allows you to set a date object's seconds to a specific value. Its syntax is as follows:

dateVariable.setSeconds(seconds)

seconds is any valid numeric integer ranging from 0 to 59, representing the seconds of the minute.

The following code section is the same as the example shown for the getSeconds() method, except that after extracting seconds, the program changes it and puts it back into vDay:

vDay = new Date("February 14, 1996 12:00:01");

seconds = vDay.getSeconds();

document.writeln("Seconds before change is " + vDay + "<br>");

seconds = 6;

vDay.setSeconds(seconds);

document.writeln("Seconds is now changed to " + vDay + "<br>");

This program's output is as follows:

Seconds before change is Wed Feb 14 12:00:01 1996

Seconds is now changed to Wed Feb 14 12:00:06 1996

Note, however, the effect of changing the seconds to an unacceptable number. If you set seconds = 6 to seconds = 124, you get the following results:

Seconds before change is Wed Feb 14 12:00:01 1996

Seconds is now changed to Wed Feb 14 12:02:04 1996

Notice that the program automatically updates the minutes. Because 124 seconds equals 2 minutes and 4 seconds, the change adds 2 minutes to the output's display of minutes.

Although the last example works quite well, use the technique of adding more than the specific range with care. JavaScript date objects are limited to dealing with dates between January 1, 1970, and December 31, 1999. If your manipulation pushes the date outside that range, the browser will crash.

setTime()

You've seen how to extract from a date object the number of milliseconds that have elapsed since January 1, 1970. Using the setTime() method, you can convert that number to a date object. The method's syntax is as follows:

dateVariable.setTime(timeValue)

timeValue is any valid numeric integer representing the number of milliseconds elapsed since January 1, 1970.

The following code section does the opposite of the example program shown for the getTime() method. This example uses the output from the getTime() example as the variable timeValue for setTime().

vDay = new Date();

document.writeln(vDay +"<br>");

vDay.setTime(824317201000);

document.writeln(vDay);

This program's output is as follows:

Mon Mar 18 16:42:27 1996

Wed Feb 14 12:00:01 1996

Notice that vDay was originally a date other than Valentine's Day 1996, but that the setTime() method changed vDay to that date. The value returned by getTime() (and used by setTime()) is commonly used to compute a new date that's some time before or after a given date, as in the following example:

vDay = new Date();

week = 7 * 24 * 60 * 60 * 1000;

document.writeln(vDay +"<br>");

vDay.setTime(vDay.getTime() + week * 2);

document.writeln(vDay);

which computes the date 14 days from today. week is the amount of milliseconds in one week (7 days, 24 hours/day, 60 minutes/hour, 60 seconds/minute, 1,000 milliseconds/second). The output,

Fri Apr 19 17:56:03 1996

Fri May 03 17:56:03 1996

shows that setTime() correctly handles date changes that span months (it could have as easily spanned years).

setYear()

You've already seen how to extract the year from a date object. The setYear() method allows you to set the year of a date object to a specific value.

The syntax for setYear() is as follows:

dateVariable.setYear(year)

year is any valid numeric integer ranging from 70 to 99, representing the current year minus 1900.

At the risk of sounding repetitive, remember that the year of a date object is restricted to the range of 1970 to 1999, inclusive. Trying to manipulate or create date objects with a year before 1970 or after 1999 will have unpredictable results (and may even crash the browser). Not making sure the date object stays within the range is probably one of the more common JavaScript programming errors.

The following code section is the same as the example for the getHours() method, except that after extracting hoursOfDay, this program changes it and puts it back into vDay:

vDay = new Date("February 14, 1996 12:00:01");

Year = vDay.getYear();

document.writeln("Year before change is " + vDay + "<br>");

Year = 75;

vDay.setYear(Year);

document.writeln("Year is now changed to " + vDay + "<br>");

This example's output is as follows:

Year before change is Wed Feb 14 12:00:01 1996

Year is now changed to Fri Feb 14 12:00:01 1975

Remember the range limitation on the values that year can use. If you enter an unacceptable number, you get an error in the browser.

toGMTString()

The toGMTString() method converts a date to a string and uses the GMT conventions. Nothing much more concrete can be said about toGMTString(). The exact format of this method's output varies according to the platform on which it executes.

The method's syntax is as follows:

dateVariable.toGMTString()

The following code section continues in the same vein as previous examples:

vDay = new Date("February 14, 1996 12:00:01");

document.writeln(vDay.toGMTString());

This script results in the following output (on a Windows 95 platform):

Wed, 14 Feb 1996 17:00:01 GMT

toLocaleString()

The toLocaleString() method is similar to toGMTString(), except it converts the given date using the rules of the current locale. Again, the exact format varies depending on the platform (and locale) under which you execute the method. Its syntax is

dateVariable.toLocaleString()

Locale means "where you are," both geographically and politically (country-wise). Dates are represented differently in different parts of the world. For example, March 14, 1996, is the way dates are represented in the United States (and other countries), whereas the same day in Europe would be represented as 14 March 1996.

Although toLocaleString() is an excellent way to have a date displayed in a user's native format, if you want to perform comparison operations, it's better to use getHours(), getMinutes(), getSeconds(), and so on.

The following example uses toLocaleString():

vDay = new Date("February 14, 1996 12:00:01")

document.writeln(vDay.toLocaleString())

This program results in the following output (on a Windows 95 computer running in the United States):

02/14/96 12:00:01

toString()

Although toLocaleString() and toGMTString() can be used to output strings for display, they aren't really "strings"—that is, they aren't true JavaScript string objects. If you remember from Chapter 11, "String Methods," JavaScript string objects have a collection of methods available that allow you to control such things as color, font size, emphasis, and so on. If you want the same kind of control over the display of a date object, you must first convert it to a string object. To manipulate the locale or GMT format of the date as a string, simply assign the output of toLocalString() or toGMTString() to a string variable, as in

strLocaleString = vDay.toLocalString();

strGMTString = vDay.toGMTString();

where vDay is your date object. If you want to manipulate the output you get from displaying the date object directly, as in

document.write(vDay);

you can use the toString() method in the same fashion:

strDay = vDay.toString();

After it's converted to a string, you can use string object methods:

document.write(strLocalString.fontcolor("red") + "<br>");

document.write(strLocaleString.fontsize(6) + "<br>");

document.write(strDay.foncolor("blue").big() + "<br>");

UTC()

UTC() (like parse()) returns a numeric value that represents the number of milliseconds that have elapsed since January 1, 1970, and the given date. However, the UTC() method handles the date in terms of Coordinated Universal Time, also known as Greenwich Mean Time, or GMT. Using this global standard makes comparison of date objects work properly, regardless of which time zone a user is in.

Note that UTC()'s syntax varies from that of all date methods expect parse():

Date.UTC(year, month, day)

or

Date.UTC(year, month, day, hours, minutes, seconds)

In this syntax, year, month, day (and optionally, hours, minutes, and seconds) are integers.

You also can use

Date.UTC(myDateObject)

where myDate is a date object (created by a call to new Date()).

The reason for this different syntax is that UTC() is a static method of Date rather than a method of a date object that has been created.

The following example uses UTC():

vDay = new Date("February 14, 1996 12:00:01");

document.writeln(Date.UTC(vDay));

This program returns the following numeric value:

824335201000

This numeric value is quite useful when combined with the setTime() method (described earlier in this chapter), which returns the numeric value to a date.

Summary

The JavaScript date object provides a means of accessing the current date and time (with respect to the user's computer) and manipulating that value. With date objects, you can track when someone last accessed your site, or how many days until a particular date in the future (or past). The methods that make up the date object provide for setting and/or getting various parts of the date, as well as converting between the user's local time and that of GMT.

Although several date methods output strings, they aren't true strings objects (as in JavaScript string objects). If you want to be able to manipulate a date as a string, you must first convert it to a string.

Review Questions

The answers to the review questions are in Appendix D.

1. What are the three types of date methods?

2. What are two examples of the use of date methods?

3. What is a locale?

4. What is GMT? What's another name for it?

5. How do you convert a date to local time? to GMT?

6. Why would you want to convert a date to GMT?

Exercises

7. Write a page that takes the user's birth date as input, and then tells them what day of the week their birthday will be on at the end of the century. For this example, assume the end of the century to be 1999.

8. Write a page that tells the user what zodiac sign a particular date falls in. Most newspapers have horoscopes that provide the dates of the 12 signs of the zodiac, or you can find them on the Internet (an exercise in itself).

9. Write a page that changes its heading based on the day of the week and whether it's a holiday.

10. Write a function that displays the number of shopping days until Christmas.

11. Write a "world clock" that displays the current time in several different cities around the globe, such as London; Washington, D.C.; Moscow; San Francisco; Tokyo; Sydney, Australia; Toronto; and Honolulu.