Working with the Date Object


Working with the Date Object

You can see the various methods of the Date object in Table 18.1, and they're great for working with dates. In fact, we've already used the Date object in Chapter 16, "Dynamic HTML: Changing Web Pages On-the-Fly"in the JavaScript Caf , which responds to the local time of day on the user 's computer to display one of three menus : breakfast , lunch , or dinner, using a Date object. Here's how that works. When you create a Date object without any parameters, the created date corresponds to the current date:

 <HTML>      <HEAD>          <TITLE>              Welcome to the JavaScript Caf          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  var currentDate = new Date()   var currentHour = currentDate.getHours()  document.write("<CENTER>")              document.write("<H1>")              document.write("Welcome to the JavaScript Caf")              document.write("</H1>")              document.write("</CENTER>")  if (currentHour < 5  currentHour > 23){  document.write("<CENTER>")          document.write("<H1>")          document.write("Sorry, we're closed now.")          document.write("</H1>")          document.write("</CENTER>")      }  .  .  . 

Here's another example. In this case, I'll use the various methods of a Date object to get the month, day, and year of the current date, using getMonth , getDay , and getYear . This causes a problem, however, because the Internet Explorer and Netscape Navigator report the year differently for getYear (see Table 18.1), so we have to treat them differently. The year 2003 is reported as 2003 from Internet Explorer's getYear , but is reported as 103 (the number of years from 1900) from Netscape Navigator's getYear . That makes the code look like this:

(Listing 18-01.html on the web site)
 <HTML>      <HEAD>          <TITLE>Getting Today's Date</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--                 function getDate()                  {                      alert(dateString())                  }  function dateString()   {   var date, text = "Today is "   date = new Date()   text += (date.getMonth() + 1) + "/"   text += date.getDate() + "/"   if (navigator.appName == "Netscape") {   text += date.getYear() + 1900   }   if (navigator.appName == "Microsoft Internet Explorer") {   text += date.getYear()   }   return(text)   }  //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>Getting Today's Date</H1>          <FORM NAME="form1">              <INPUT TYPE="BUTTON" VALUE="Get Date" ONCLICK="getDate()">          </FORM>      </BODY>  </HTML> 

You can see the results in Figure 18.1.

Figure 18.1. Displaying the date.

graphics/18fig01.gif

You can fix the problem with getYear by using getFullYear instead, which returns the full four-digit year. In fact, getYear is considered obsolete because of Y2K issues, so you should use getFullYear :

 <HTML>      <HEAD>          <TITLE>Getting Today's Date</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--                 function getDate()                  {                      alert(dateString())                  }             function dateString()             {                  var date, text = "Today is "                  date = new Date()                  text += (date.getMonth() + 1) + "/"                  text += date.getDate() + "/"  text += date.getFullYear()  return(text)              }              //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>Getting Today's Date</H1>          <FORM NAME="form1">              <INPUT TYPE="BUTTON" VALUE="Get Date" ONCLICK="getDate()">          </FORM>      </BODY>  </HTML> 

In this example, I've used methods such as getMonth to extract data from a Date object, but you also can just use a method such as toString to get the date in text string format:

 function dateString()  {      var date      date = new Date()  return(date.toString())  } 

However, the format of this text string varies by browser. Here's what you get from the Netscape Navigator:

 Tue Mar 26 14:20:18 GMT-0500 (Eastern Standard Time) 2003 

And here's what you get from the Internet Explorer:

 Tue Mar 26 14:20:07 EST 2003 

Creating an Alarm Clock

Date objects are useful for many applications that need to keep track of the time, as you can imagine. Here's an alarm clock program, for example, which you can see at work in Figure 18.2.

Figure 18.2. An alarm clock.

graphics/18fig02.gif

This example is just a demo, so it's not written to understand the difference between a.m. and p.m., but it will display the current time and has a useable "alarm," which you can toggle on and off with the radio buttons at the lower left. When the alarm is on and the current time is after the time set in the text field at left for the alarm setting, the alarm goes off by making the page flash, alternating between a red and white background, until you turn the alarm off.

Here's how this example works. I use setInterval to call a function named showTime every half second:

 var intervalID = window.setInterval("showTime()", 500) 

In the showTime function, we get the time and display it like this in a <DIV> element whose style I've set to 48-point font:

 function showTime()  {  var d = new Date()   document.getElementById("div1").innerHTML = d.toLocaleTimeString()  .          .          .  } 

We can then compare the time to the alarm setting using getHour , getMinute , and so on; but in this example, I'm going to do a simple string comparison (which is why you shouldn't trust this demo to know the difference between a.m. and p.m.) to see whether we should turn on the alarm:

 function showTime()  {      var d = new Date()      document.getElementById("div1").innerHTML = d.toLocaleTimeString()  if(on && d.toLocaleTimeString() > document.form1.text1.value){   if(color == "white"){   color = "red"   } else {   color = "white"   }   document.body.bgColor = color   }  } 

That's it. Here's the whole code, including the support for the radio buttons that turn the alarm on and off (if you're using Netscape Navigator, you have to use version 6 or later):

(Listing 18-02.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Alarm Clock          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             var intervalID = window.setInterval("showTime()", 500), on = false, graphics/ccc.gif color="white"                   function showTime()              {                  var d = new Date()                  document.getElementById("div1").innerHTML = d.toLocaleTimeString()                  if(on && d.toLocaleTimeString() > document.form1.text1.value){                      if(color == "white"){                          color = "red"                      } else {                          color = "white"                      }                      document.body.bgColor = color                     }              }              function alarmOn()              {                     on = true              }              function alarmOff()              {                     on = false                     document.body.bgColor = "white"              }              // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Alarm Clock</H1>          <FORM NAME="form1">              <DIV ID="div1" STYLE="font-size:48pt"></DIV>              <BR>              Alarm Setting: <INPUT TYPE="TEXT" NAME="text1">              <BR>              <INPUT TYPE="RADIO" NAME="onoff" ONCLICK="alarmOn()">On</INPUT>              <INPUT TYPE="RADIO" NAME="onoff" ONCLICK="alarmOff()" CHECKED>Off</INPUT>          </FORM>      </BODY>  </HTML> 

Adding and Subtracting Dates

Another useful aspect of using the Date object is to add and subtract dates. That's usually done by converting both dates to milliseconds (with getTime , which returns a millisecond count measured in total milliseconds since 1/1/70) and working with those values, and then converting the resulting number of milliseconds back to a time.

To subtract dates, you just have to subtract the millisecond values to find the time difference in milliseconds. To add a specified amount of time to a date, you can convert the date to milliseconds, add the number of milliseconds you want to it, and then convert the result back to a date by creating a new Date object ( var date1 = new Date( milliseconds ) ) or setting the date in an existing Date object ( date1.setTime( milliseconds ) ).

Here's an examplethe Date Subtractorwhich enables you to subtract one date from another and gives you the number of intervening days. You can see this program at work in Figure 18.3, where I subtracting two dates and get the resulting time difference in days.

Figure 18.3. Subtracting dates.

graphics/18fig03.gif

All we have to do in this case is to convert the two dates into milliseconds since 1/1/1970. I then subtract those millisecond values (using the Math.abs absolute value method we'll see in the next chapter to get a positive value) and convert the result to days (using the Math.floor method we'll also see in the next chapter to round off the result):

(Listing 18-03.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Date Subtractor          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function showTime()   {   var date1, date2   date1 = new Date(document.form1.text1.value)   date2 = new Date(document.form1.text2.value)   var difference   difference = Math.abs(date1.getTime() - date2.getTime())   document.form1.text3.value =   Math.floor(difference / (1000 * 60 * 60 * 24)) + " days"   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Date Subtractor</H1>          <FORM NAME="form1">              <CENTER>              <INPUT TYPE="TEXT" NAME="text1">              <BR>              -             <BR>              <INPUT TYPE="TEXT" NAME="text2">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="showTime()"  VALUE="&nbsp;&nbsp;=&nbsp;&nbsp;">              <BR>              <INPUT TYPE="TEXT" NAME="text3">              </CENTER>          </FORM>      </BODY>  </HTML> 

That's all there is to it.

Handling Date Strings

Some JavaScript properties, such as fileCreatedDate , lastModified , and fileModifiedDate (see Table 9.2) hold date strings in Date object format. You can use those date strings when you create a new Date object, like this:

 var lastUpdated = new Date(document.fileCreatedDate) 

Here's an example that does that for the last-modified date of a document. In this case, the code just displays when the document was last modified:

(Listing 18-04.html on the web site)
 <HTML>      <HEAD>          <TITLE>Getting Last Updated Dates</TITLE>      </HEAD>      <BODY>          <H1>Getting Last Updated Dates</H1>          <FORM NAME="form1">              <INPUT NAME="text1" SIZE="50"></INPUT>          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--  var lastUpdated = new Date(document.lastModified)   month = lastUpdated.getMonth() + 1   date = lastUpdated.getDate()   year = lastUpdated.getFullYear()   document.form1.text1.value =   "This document was last updated " + month + "/" + date + "/" + year  //-->          </SCRIPT>      </BODY>  </HTML> 

You can see the results in Figure 18.4, where the document's last-modified time appears.

Figure 18.4. Displaying a document's last-modified time.

graphics/18fig04.gif

Checking Date Format

Before using date strings when you create Date objects (such as var date1 = new Date( dateString ) ), it's worth remembering that not all date strings in all formats are acceptable to JavaScript. One good way to check the format of date strings is with regular expressions , which we'll see in Chapter 20, "The RegExp Object: Working with Regular Expressions." Regular expressions enable you to specify patterns that match or don't match text, letting you know whether the text conforms to what you want.

Here, for example, I'm only allowing the user to enter date strings made up of one or two digits, followed by a slash (/), followed by one or two digits, followed by a slash, followed by two or four digits for the year:

(Listing 18-05.html on the web site)
 <HTML>      <HEAD>          <TITLE>Checking Dates</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function checker()   {   var regExp1 = /^(\d{1,2})\/(\d{1,2})\/(\d{2})$/   var regExp2 = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/   var resultArray1 = document.form1.text1.value.match(regExp1)   var resultArray2 = document.form1.text1.value.match(regExp2)   if (resultArray1 == null && resultArray2 == null) {   alert("Sorry, that's not in valid date format.")   } else {   alert("That's in valid date format.")   }   }  //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>Checking Dates</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1"></INPUT>              <INPUT TYPE="BUTTON" VALUE="Check Date" ONCLICK="checker()">          </FORM>      </BODY>  </HTML> 

You can see the results in Figure 18.5, where the code is indicating that the user has not entered a valid date. (Note that this example doesn't check whether a date is completely validit doesn't check whether the user entered 13 for the month, and so on).

Figure 18.5. Checking date format.

graphics/18fig05.gif

Creating Custom Date Strings

Although you can use Date object methods such as toString to get the date in string format, that format varies between browsers. It's usually easier to put together date strings yourself if you want to be consistent across all browsers. The following example puts together a date string representing the current date:

(Listing 18-06.html on the web site)
 <HTML>      <HEAD>          <TITLE>Getting Today's Date</TITLE>          <SCRIPT LANGUAGE="JavaScript">               <!--  function getDate()   {   month = new Array(12)   day = new Array(7)   month[0] = "January"   month[1] = "February"   month[2] = "March"   month[3] = "April"   month[4] = "May"   month[5] = "June"   month[6] = "July"   month[7] = "August"   month[8] = "September"   month[9] = "October"   month[10] = "November"   month[11] = "December"   day[0] = "Sunday"   day[1] = "Monday"   day[2] = "Tuesday"   day[3] = "Wednesday"   day[4] = "Thursday"   day[5] = "Friday"   day[6] = "Saturday"   var date = new Date()   document.form1.text1.value = "Today is " + day[date.getDay()] + ", "   + month[date.getMonth()] + " "   + date.getDate() + ", " + date.getFullYear()   }  //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>Getting Today's Date</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" SIZE="60"></INPUT>              <BR>              <INPUT TYPE="BUTTON" VALUE="Get Date" ONCLICK="getDate()">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 18.6, where the code displays the date in a standard format.

Figure 18.6. Formatting a date string.

graphics/18fig06.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

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