As we’ll see, the Date object provides a number of methods for getting or setting spe-cific information about the date and time.. Because client-side JavaScript programs run on a browse
Trang 19.4 The Date Object
JavaScript provides the Date object for manipulating date and time.2 Like the String and
Array objects, you can create as many instances as you like.
As we’ll see, the Date object provides a number of methods for getting or setting
spe-cific information about the date and time The date is based on the UNIX date starting
at January 1, 1970 (in Greenwich Mean Time3 [GMT]), and doesn’t support dates before
that time Figure 9.19 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)
Because 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.20 shows a typical date and time control panel
2 For more information about the time and date, see http://www.timeanddate.com/worldclock/.
3 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.19 24-hour world time zones map with current time Courtesy of
http://www.worldtimezone.com/index24.html.
Trang 2If 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; shown in Example 9.16.
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.
Figure 9.20 The computer’s date and time settings.
E X A M P L E 9 1 6
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new Date(milliseconds)
Here are a few examples of instantiating a date:
mydate = new Date()
mydate = new Date("March 15, 2010 09:25:00")
mydate = new Date(“March 15, 2010”)
mydate = new Date(10,2,15)
mydate = new Date(10,2,15,9,25,0)
mydate = new Date(500);
Trang 3Table 9.3 Date Object Methods
getDate Returns the day of the month (1–31)
getDay Returns the day of the week (0–6); 0 is Sunday, 1 is Monday,
and so on
getFullYear Returns the year with four 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, and
so on
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
getUTCDate() Returns the day of the month
getUTCDay() 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
Trang 4setTime() 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 the 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
E X A M P L E 9 1 7
<html>
<head><title>Time and Date</title></head>
<body bgcolor="aqua"><h2>Date and Time</h2>
<big>
<script type="text/javascript">
1 var now = new Date(); // Now is an instance of a Date object
document.write("<b>Local time:</b> " + now + "<br />");
Continues
Table 9.3 Date Object Methods (continued)
Trang 5JavaScript 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
informa-tion in Table 9.4 might be helpful in converting milliseconds to minutes, hours, days,
and so forth
document.write("The full year is " + year +"<br />");
document.write("<b>The time is:</b> " +
hours + ":" + minutes + ":" + seconds);
</script>
</big>
</body>
</html>
E X P L A N A T I O N
1 A new Date object called now is created It contains a string with the current date
and time: Mon Aug 10 18:22:36 GMT-0700(Pacific Daylight Time)
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,
2010 The output is shown in Figure 9.21.
Figure 9.21 Date object and its methods.
E X A M P L E 9 1 7 (C O N T I N U E D)
Trang 6Table 9.4 Basic Units of Time
Unit of Time Milliseconds
1 second 1,000
1 minute second * 60 (1,000 * 60)
1 hour minute * 60 (1,000 * 60 * 60)
1 day hour * 24 (1,000 * 60 * 60 * 24 )
1 week day * 7 (1,000 * 60 * 60 * 24 * 7 )
E X A M P L E 9 1 8
<html>
<head><title>Countdown 'til Christmas</title></head>
<body bgColor="#00FF99">
<font face="arial" size=5 color=red>
<script type="text/javascript">
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>
</font>
</body>
</html>
E X P L A N A T I O N
1 A new Date object called today is created.
2 The getFullYear() method returns the year as 2010
3 Another Date object called future is created It will contain the future date,
Christ-mas, passed as its argument
4 The difference between the future time and the present time is calculated and
re-turned 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.22)
Trang 7with the prototype Property
All objects have a prototype property that allows you to extend the capabilities of the
object With the Date object’s prototype property, you can customize the time and the date
by providing new methods and properties that will be inherited by all instances of this
object Because the Date object provides methods that return zero-based months, weeks,
years, and other measures, you might want to create a prototype method where “January”
is month number 1 instead of 0, and the day is “Monday” instead of 1, and so on.
Figure 9.22 The number of days between two dates has been calculated.
E X A M P L E 9 1 9
<html>
<head><title>The Prototype Property</title>
<script type = "text/javascript">
// Customize the Date
names[0]="Sunday";
names[1]="Monday";
names[2]="Tuesday";
names[3]="Wednesday";
names[4]="Thursday";
names[5]="Friday";
names[6]="Saturday";
}
</script>
</head>
<body bgcolor="pink">
<font face="arial">
<big>
<div align="center">
<script type="text/javascript">
7 document.write("Today is " + today.DayOfWeek() + ".<br />");
</script>
</div>
</big>
</font>
</body>
</html>
Trang 89.5 The Math Object
The Math object allows you to work with more advanced arithmetic calculations, such
as square root, trigonometric functions, logarithms, and random numbers, than are
pro-vided by the basic numeric operators If you are doing simple calculations, you really
won’t need it
Unlike other objects, you don’t have to create an instance of the Math object with the
new keyword It is a built-in object and has a number of properties (see Table 9.5) and
methods (see Table 9.6) The Math object always starts with an uppercase M
E X P L A N A T I O N
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
week-Day Now the Date object has a new method that will be inherited by all objects
created from the Date() constructor The capabilities of the Date object have been
extended to provide a method that will return the name of the weekday (See
Chapter 8 for more on prototypes.)
6 A new Date object is created with the Date() constructor function.
7 The new prototype method is called, and returns the string value of today’s date,
“Saturday” (see Figure 9.23)
Figure 9.23 The day is converted to a string using a prototype.
Table 9.5 Math Object Properties
Math.E 2.718281828459045091 Euler’s constant, the base of
natural logarithms
Math.LN2 0.6931471805599452862 Natural log of 2
Math.LN10 2.302585092994045901 Natural log of 10
Continues