9.4 The Date Object


9.4 The Date Object

JavaScript provides the Date object for manipulating date and time. [3] Like the String and Array objects, you can create as many instances as you like.

[3] For more information about the time and date, see http://www.timeanddate.com/worldclock/.

As we'll see, the Date object provides a number of methods for getting or setting specific information about the date and time. The date is based on the UNIX date starting at January 1, 1970 (in Greenwich Mean Time [4] [GMT]), and doesn't support dates before that time. Figure 9.12 gives you an idea of the difference between GMT and local time. Time is measured in milliseconds (one millisecond is one thousandth of a second). Since client-side JavaScript programs run on a browser, the Date object returns times and dates that are local to the browser, not the server. Of course, if the computer is not set to the correct time, then the Date object won't produce the expected results. Figure 9.13 shows a typical date and time control panel.

[4] Greenwich Mean Time (GMT) is now called Universal Coordinate Time (UTC). The current time in Greenwich, England is five hours + New York's present time, or eight hours + San Francisco's present time.

Figure 9.12. 24- hour world time zones map with current time. Courtesy of http://www.worldtimezone.com/index24.html.

graphics/09fig12.jpg

Figure 9.13. The computer's date and time settings.

graphics/09fig13.jpg

If no arguments are passed to the Date object constructor, it returns the local date and time (based on the accuracy of the clock on your client machine). There are five formats that can be passed as arguments when creating a Date object. They are shown in Example 9.12.

Example 9.12
 var Date = new Date();   // The  new constructor returns a Date  object. var Date = new Date("July 4, 2004, 6:25:22"); var Date = new Date("July 4, 2004"); var Date = new Date(2004, 7, 4, 6, 25, 22); var Date = new Date(2004, 7, 4); var Date = new Date(Milliseconds); 

9.4.1 Using the Date Object Methods

The Date object comes with a large number of methods (see Table 9.3) and only a prototype property. For browser versions supporting Date methods, see http://www.w3schools.com/js/js_datetime.asp.

Table 9.3. Date object methods.

Method

What It Does

getDate

Returns the day of the month (1 “31)

getDay

Returns the day of the week (0 “6); 0 is Sunday, 1 is Monday, etc.

getFullYear

Returns the year with 4 digits [*]

getHours

Returns the hour (0 “23)

getMilliseconds

Returns the millisecond [*]

getMinutes

Returns hours since midnight (0 “23)

getMonth

Returns number of month (0 “11); 0 is January, 1 is February, etc.

getSeconds

Returns the second (0 “59)

getTime

Returns number of milliseconds since January 1, 1970

getTimeZoneOffset

Returns the difference in minutes between current time on local computer and UTC (Universal Coordinated Time)

getUTCDate()

Returns the day of the month [*]

getUTDDay()

Returns the day of the week converted to universal time [*]

get UTCFullYear()

Returns the year in four digits converted to universal time [*]

getUTCHours()

Returns the hour converted to universal time [*]

getUTCMilliseconds()

Returns the millisecond converted to universal time [*]

parse()

Converts the passed-in string date to milliseconds since January 1, 1970

setDate(value)

Sets day of the month (1 “31)

setFullYear()

Sets the year as a four-digit number [*]

setHours()

Sets the hour within the day (0 “23)

setHours(hr,min,sec,msec)

Sets hour in local or UTC time

setMilliseconds

Sets the millisecond [*]

setMinutes(min,sec, msec)

Sets minute in local time or UTC

setMonth(month,date)

Sets month in local time

setSeconds()

Sets the second

setTime()

Sets time from January 1, 1970, in milliseconds

setUTCdate()

Sets the day of the month in universal time

setUTCFullYear()

Sets the year as a four-digit number in universal time [*]

setUTCHours()

Sets the hour in universal time [*]

setUTCMilliseconds()

Sets the millisecond in universal time [*]

setUTCMinutes()

Sets the minute in universal time [*]

setUTCMonth()

Sets the month in universal time [*]

setUTCSeconds()

Sets the second in universal time [*]

setYear()

Sets the number of years since 1900 (00 “99)

toGMTString()

Returns the date string in universal format

toLocaleString

Returns string representing date and time based on locale of computer as 10/09/99 12:43:22

toSource

Returns the source of the Date object [*]

toString

Returns string representing date and time

toUTCString

Returns string representing date and time as 10/09/99 12:43:22 in universal time [*]

UTC ()

Converts comma-delimited values to milliseconds [*]

valueOf()

Returns the equivalence of the Date object in milliseconds [*]

[*] Starting with Netscape 4.0 and IE 4.0.

Example 9.13
 <html>     <head><title>Time and Date</title></head>     <body bgcolor="lightblue"><h2>Date and Time</h2>     <script language="JavaScript"> 1  var now = new Date();  //  Now is an instance of a Date object  document.write("<font size='+1'>");         document.write("<b>Local time:</b> " + now + "<br>"); 2  var hours=now.getHours();  3  var minutes=now.getMinutes();  4  var seconds=now.getSeconds();  5  var year=now.getFullYear();  document.write("The full year is " +  year  +"<br>");         document.write("<b>The time is:</b> " +  hours + ":" + minutes + ":" + seconds  );                 document.write("</font>");     </script>     </body>     </html> 

EXPLANATION

  1. A new Date object called now is created. It contains a string: Thu Feb 6 20:02:02 PST 2003.

  2. The variable called hours is assigned the return value of the getHours() method.

  3. The variable called minutes is assigned the return value of the getMinutes() method.

  4. The variable called seconds is assigned the return value of the getSeconds() method.

  5. The variable called year is assigned the return value of the getFullYear() method, 2003 . The output is shown in Figure 9.14.

    Figure 9.14. Output from Example 9.13.

    graphics/09fig14.jpg

9.4.2 Manipulating the Date and Time

JavaScript stores dates in milliseconds, so if you have more complicated calculations to perform, such as the number of days before a date, or between two dates, the information in Table 9.4 might be helpful in converting milliseconds to minutes, hours, days, and so forth.

Table 9.4. Basic units of time.

Unit of Time

Milliseconds

 

1 second

1000

 

1 minute

second * 60

(1000 * 60)

1 hour

minute * 60

(1000 * 60 * 60)

1 day

hour * 24

(1000 * 60 * 60 * 24 )

1 week

day * 7

(1000 * 60 * 60 * 24 * 7 )

Example 9.14
 <html><head><title>Countdown 'till Christmas</title></head>     <body bgColor="#00FF99">     <font face="arial" size=5 color=red>     <script language="JavaScript"> 1  var today = new Date();  2       var fullyear =  today.getFullYear();  3       var future =  new Date("December 25, "+ fullyear);  4       var diff =  future.getTime() - today.getTime();  //  Number of milliseconds  5       var days =  Math.floor(diff / (1000 * 60 * 60 * 24 ));  //  Convert to days  6  var str="Only <u>" + days + "</u>  shopping days left   \'til Christmas! ";  document.write(str+"<br>");     </script>     </body>     </html> 

EXPLANATION

  1. A new Date object called today is created.

  2. The getFullYear() method returns the year as 2003.

  3. Another Date object called future is created. It will contain the future date, Christmas, passed as its argument.

  4. The difference between the future time and the present time is calculated and returned in milliseconds with the getTime() method.

  5. The Math object is used to round down the result of converting milliseconds to days.

  6. This string contains the number of days between the present date and Christmas. (See Figure 9.15.)

    Figure 9.15. The number of days between two dates has been calculated.

    graphics/09fig15.jpg

9.4.3 Customizing the Date Object with the prototype Property

The Date object has a prototype property that allows you to extend the capabilities of the object. You can customize the time and the date by providing new methods and properties that will be inherited by all instances of this object. Since the Date object provides methods that return zero-based months, weeks, years, and other measures you may want to create a prototype method where "January" is month number 1 instead of 0, and the day is "Monday" instead of 1, etc.

Example 9.15
 <html><head><title>The Prototype Property</title>     <script language = "javascript">     //  Customize the Date  1   function weekDay(){ 2       var now = this.getDay(); 3       var names = new Array(7);         names[0]="Sunday";         names[1]="Monday";         names[2]="Tuesday";         names[3]="Wednesday";         names[4]="Thursday";         names[5]="Friday";         names[6]="Saturday"; 4  return(names[now]);   }  5  Date.prototype.DayOfWeek=weekDay;  </script>     </head>     <body bgcolor="pink">     <font face="arial" size="+1">     <center>     <script language="JavaScript"> 6  var today=new Date();  7       document.write("Today is " +  today.DayOfWeek()  + ".<br>");     </script>      </body></html> 

EXPLANATION

  1. The function called weekday() is defined.

  2. The variable now is assigned a number representing the day of the week, where 0 is Sunday.

  3. A new Array object called names is created. It will contain seven elements. Each element will be assigned the name of the weekday, e.g., "Sunday" .

  4. The value in now , a number between 0 and 6, will be used as an index in the names array. If now is 6, then the value of names[6], "Saturday" , will be returned.

  5. A prototype method called DayOfWeek is assigned the name of the function that defines the method.

  6. A new Date object is created with the Date() constructor method.

  7. The new prototyped method is called, and returns the string value of today's date, "Saturday" . (See Figure 9.16.) The capabilities of the Date object have been extended to provide a method that will return the name of the weekday.

    Figure 9.16. The day is converted to a string.

    graphics/09fig16.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net