Приглашаем посетить
Литература (lit-info.ru)

12.1 An introduction to date and time functions

Table of Contents

Previous Next

12.1 An introduction to date and time functions

12.1.1 Working with the date object

In Chapter 7, you learned how to use the time functions getTime() and setTime() to set and change the expiry date of a cookie. These two functions are designed to manipulate the time stores in a date object. The following is typical example code used to get the date and time of yesterday.



1: dateObj = new Date()
2: currentTime = dateObj.getTime()
3: yesterdayDate = currentDate  1000*60*60*24

The first line is used to create a new object variable (or instance) named dateObj from the date object provided by the browser. Once we have done that, we can access all the methods of the object from the dateObj variable as demonstrated in line 2 (i.e., the getTime() function is a member of the date object). This is a great strength of the so-called object-oriented programming design. By using a dot (.) operator, object variables can call all member functions (or methods) of their parent. It took more than 10 years for the traditional structural programming world to adopt this new programming approach to fight against program corruptions. Only object variables can call member functions and therefore prevent global, and large-scale, damage to programs and/or systems.

To continue the date and time discussion, let's consider the following example ex12-01.htm:



Example: ex12-01.htm - Date And Time Functions

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Date And Time Functions -- ex1201.htm </title></head>
 6: <body style="background:#000088;text-align:center;font-family:arial">
 7: <script>
 8:  lMsg = '<div style="font-size:18pt;color:#ffff00;font-weight:bold"><br />'
 9:   lMsg = lMsg +"The Use Of getTime() and setTime() Functions<br /><br />"
10:  dateObj = new Date()
11:  currentTime = dateObj.getTime()
12:   lMsg = lMsg +"Today in milliseconds is: " +currentTime+"<br /><br />"
13:   lMsg = lMsg + "Today is: "+ dateObj +"<br />"
14:  yesterdayTime= dateObj.setTime(currentTime - 1000*60*60*24)
15:   lMsg = lMsg + "Yesterday is: "+ dateObj +"<br />"
16:  tomorrowTime = dateObj.setTime(currentTime + 1000*60*60*24)
17:   lMsg = lMsg + "Tomorrow is: "+ dateObj +"</div>"
18:  document.write(lMsg)
19: </script>
20: </body>
21: </html>

The getTime() function (line 11) returns an integer value representing the number of milliseconds between midnight of the zero time (the first day of January 1970) and the time stores in the date object. The range of this value is approximately 285,616 years either side (positive and negative) from the zero time. Thus a negative number indicates a date prior to 1970.

By creating a new object in line 10, we have an object with an internal time string. The variable currentTime has a value of the local date and time in milliseconds of the date object. By subtracting 1000*60*60*24 (one day), this value is used to find the date of yesterday (line 14). You can generate and output the normal date and time of yesterday as illustrated in line 15. The same technique is used to calculate tomorrow's date and time (lines 1617). A screen shot is shown in Fig. 12.1.

Figure 12.1. ex12-01.htm

graphics/12fig01.jpg


Manipulating the date and time in milliseconds is not very convenient and sometimes difficult to understand. In practice, we need to convert (or redefine) these values to a format that we are familiar with.

12.1.2 Setting date and time at creation level

By default, calling the statement dateObj = new Date() with no argument is equivalent to storing the current date in the variable dateObj. To set the date and time at the creation level, you can use the following numeric and string formats:



new Date("Month dd, yyyy hh:mm:ss")  String format,
e.g., var dateObj=new Date("October 24, 2004 13:48:00")

new Date("Month dd, yyyy")  String format,
e.g., var dateObj=new Date("October 24, 2004")

new Date(yy,mm,dd,hh,mm,ss)  Numeric format,
e.g., var my_date=new Date(2004,09,24,13,48,00)

new Date(yyyy,mm,dd)  Numeric format,
e.g., var dateObj=new Date(2004,09,24)

Since the numeric month starts from zero, the true value of 09 is actually October. The next example ex12-02.htm is used to put these settings into action.



Example: ex12-02.htm - Create The Date Object Variable

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Create The Date Object Variable -- ex1202.htm</title></head>
 6: <body style="background:#000088;text-align:center;font-family:arial;
 7:     font-size:16pt;color:#ffff00">
 8: <script>
 9:   var dateObj=new Date()
10:   document.write("<br />The Current Date and Time is<br />")
11:   document.write(dateObj+"<br /><br /><br />")
12:
13:   document.write("Some Date and Time Settings are <br /><br />")
14:   dateObj=new Date("October 24, 2003 13:48:00")
15:     document.write(dateObj+"<br />")
16:   dateObj=new Date("October 24, 2004")
17:     document.write(dateObj+"<br />")
18:   dateObj=new Date(2005,09,24,13,48,00)
19:     document.write(dateObj+"<br />")
20:   dateObj=new Date(2006,09,24)
21:     document.write(dateObj+"<br />")
22: </script>
23: </body>
24: </html>

If you call the date object with no argument as demonstrated in line 9, the current date and time value (as a string) is stored in the variable dateObj. A simple document.write() function call as in line 11 outputs the current date and time such as



Fri Oct 24 11:40:00 UTC+0100 2003

UTC represents Universal Coordinate Time, which is similar to GMT (Greenwich Mean Time). If you are using NS browsers, the output string is



Fri Oct 24 13:48:00 GMT+0100 (GMT Daylight Time) 2003

in GMT format. We generally refer to this string as the time string stored in the date object (or variable). Lines 1421 illustrate some different settings for this time string. A screen shot is shown in Fig. 12.2.

Figure 12.2. ex12-02.htm

graphics/12fig02.jpg


If you don't feel comfortable with the UTC or GMT time format, you can add the function (or method) toLocaleString()at the end of the date object. This changes the time format in the current local default format. For example, if you are in Europe and have changed lines 911 in ex12-02.htm to



 9: var dateObj=new Date()
10: document.write("<br />The Current Date and Time is<br />")
11: document.write(dateObj.toLocaleString() +"<br /><br /><br />")

you will see the date and time in local format as (see ex12-02a.htm in the companion Web site)



The Current Date and Time is
20 September 2003 00:24:11

12.1.3 Basic date and time functions

Associated with each date object or object variables, there are a number of built-in functions ready for you to use. For example, the following are some of the most frequently used date functions on the Web.

  • getFullYear() Returns the year stored in the date object.

  • getMonth() Returns the month value in the date object.

  • getDate() Returns the day of the month.

  • getDay() Returns the day of the week.

From an object-oriented programming point of view, member functions of an object are usually called methods. To use these functions, let's take a look at the next example, ex12-03.htm. It gets today's date from the date object.



Example: ex12-03.htm - Date Functions

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Date Functions -- ex1203.htm </title></head>
 6: <body style="background:#000088;text-align:center;font-family:arial;
 7:     font-size:16pt;color:#ffff00">
 8: <script>
 9:  cDate = new Date()
10:  document.write("Getting Today's Date From The Date Object<br /><br />")
11:  document.write("The Day of The Week = "+cDate.getDay()+"<br />")
12:  document.write("The Date of The Month = "+cDate.getDate()+"<br />")
13:  document.write("The Current Month = "+(cDate.getMonth()+1)+"<br />")
14:  document.write("The Current Year = "+cDate.getFullYear()+"<br />")
15: </script>
16: </body>
17: </html>

Line 9 is used to declare a date object variable called cDate. This variable has all the built-in functions and properties that are associated with the object. From lines 1014, we can see how this object variable is used to get each item of today's date.

Note that all these functions return numerical values. Since the getMonth() function starts from the value 0, we need to increase it by 1 (line 13) to reflect the true calendar month. A screen shot of this page is shown in Fig. 12.3.

Figure 12.3. ex12-03.htm

graphics/12fig03.jpg


Some older Web browsers may use the function getYear() instead of the getFullYear(). The function getYear() is obsolete since it can only return the value representing the difference between the stored year and 1900. For example, 1999 is returned as 99, and 2004 is returned as 104. This problem is normally referred to a "millennium bug" and special care is needed.

Compared to the date, the time functions are simpler. For each date object variable, we have the following time functions:

  • getHours() Returns the hours in the date object.

  • GetMinutes() Returns the number of minutes past the hour.

  • GetSeconds() Returns the number of seconds past the minute.

These functions are designed to get the local time stored in our computer. A simple demonstration of how to use them is shown in ex12-04.htm.



Example: ex12-04.htm - Time Functions

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Time Functions -- ex1204.htm </title></head>
 6: <body style="background:#000088;text-align:center;font-family:arial;
 7:     font-size:16pt;color:#ffff00">
 8: <script>
 9:  cDate = new Date()
10:  document.write("Getting Local Time From The Date Object<br /><br />")
11:  document.write("The Current Hour = "+cDate.getHours()+"<br />")
12:  document.write("The Current Minutes = "+cDate.getMinutes()+"<br />")
13:  document.write("The Current Seconds = "+cDate.getSeconds()+"<br />")
14: </script>
15: </body>
16: </html>

Again, we first create a date object variable (cDate) in line 9. Then we can directly call the time functions as member functions of the object. A screen shot of this page at work is shown in Fig. 12.4. If you refresh this page, you should notice the changes on "The Current Seconds" field.

Figure 12.4. ex12-04.htm

graphics/12fig04.jpg


For each get function, we also have a corresponding set function in the date object. They are:

  • setFullYear() Sets the year of the date object.

  • setMonth() Sets the month value of the date object.

  • setDate() Sets the day of the month.

  • setDay() Sets the day of the week.

  • setHours() Sets the hours of the date object.

  • setMinutes() Sets the minutes of the date object.

  • setSeconds() Sets the seconds of the date object.

Together with the get functions, they form the basic date and time functions and are embedded inside the browser. As a simple demonstration of how to use them, we have listed the script part of example ex12-05.htm in the listing ex12-01.txt.



Listing: ex12-01.txt - Code Fragment Of ex1205.htm

 1: <script>
 2:  dateObj = new Date()
 3:  dateObj.setFullYear(2003)
 4:  dateObj.setMonth(11)
 5:  dateObj.setDate(31)
 6:  dateObj.setHours(0)
 7:  dateObj.setMinutes(0)
 8:  dateObj.setSeconds(0)
 9:  document.write(dateObj)
10: </script>

Once you have created the date object (dateObj) in line 2, you can set the date and time of this object individually. For example, setMonth(11) sets the month as December. The output statement in line 9 writes the following time string to the browser screen:



Wed Dec 31 00:00:00 UTC 2003

or the following string if you are using NS6:



Wed Dec 31 00:00:00 GMT+0000 (GMT Standard Time) 2003

Now, let's consider some applications of the date and time functions.

    Table of Contents

    Previous Next