Using the Date Object
(Lesson 9)

We continue our discussion of the Date object in this lesson and learn how to make clocks. We will also learn a different way of doing conditional expressions and see how to do a little Date arithmetic.


Our First Clock

Here's the script that we came up with to display time in problem assignment number 4 in our last lesson.

 <SCRIPT language="JavaScript">
 <!--
 var time = new Date()
 var hour = time.getHours()
 var min = time.getMinutes()
 var sec = time.getSeconds()
 document.write(hour + ":" + min + ":" + sec)
 //-->
 </SCRIPT>

The problem with using this script for the basis of a clock is that numbers less than 10 for the minutes and seconds are not displayed with a '0' in front of them. This can be solved by using the if statement as follows:

 <SCRIPT language="JavaScript">
 <!--
 var time = new Date()
 var hr = time.getHours()
 var min = time.getMinutes()
 var sec = time.getSeconds()
 if(hr < 10){
   hr = " " + hr
   }
 if(min < 10){
   min = "0" + min
   }
 if(sec < 10){
   sec = "0" + sec
   } 
 document.write(hr + ":" + min + ":" + sec)
 //-->
 </SCRIPT>

I also put a blank space in front of the hour when it is below 10. I think this works better for a clock. Now all that is left to do is to put this script in a function that displays the results in a text box of a form. We use the setTimeout() function that we learned about in Lesson 7 to call the function every second to display time. Remember that the second parameter of the function determines the amount of time in milliseconds that goes by before the function specified in the first parameter is called. So, we want to use a value of 1000 for the this parameter.

Here is our completed clock() function that is put between the <SCRIPT> tags in the HEAD section.

 function clock(){
  var time = new Date()
  var hr = time.getHours()
  var min = time.getMinutes()
  var sec = time.getSeconds()
  if(hr < 10){
    hr = " " + hr
    }
  if(min < 10){
    min = "0" + min
    }
  if(sec < 10){
    sec = "0" + sec
    } 
  document.clock.digits.value = hr + ":" + min + ":" + sec
  setTimeout("clock()", 1000)
  }

Here is the HTML code for the form that is used in the BODY section of the document to display the results from our function.

 <FORM name="clock">
 <FONT face="Courier New,Courier" size=4>
 <INPUT type="text"  name="digits"
    size=8 maxlength=8 value="Loading">
 </FONT>
 </FORM>

I like to use a fixed width font for clocks when displayed in a form. This seems to make the clock look better in a Netscape browser but has little effect in Internet Explorer. The final bit of code needed to make this work is to put
onLoad = "clock()"
in the <BODY> tag.

Here is the clock that we get when we set up our document as described above.

   

This clock displays in the 24 hour format. If you want to make a 12 hour clock then you will need to add a couple of more if statements. One is needed to display "am" or "pm" depending on the time of day and one to change the hour variable so that it only displays the numbers 1 through 12. Also the width of the text box on the form will need to be adjusted. Seems that this project would be a good homework assignment.


Conditional Expressions

There is a different way of writing an if then else statement if you want to assign one of two values to a variable. You will often see this technique used in lieu of the way we wrote our if statements above. Lets look at how our clock function would look if we used the conditional expression.

 function clock(){
  var time = new Date()
  var hr = time.getHours()
  var min = time.getMinutes()
  var sec = time.getSeconds()

  hr = ((hr < 10) ? " " : "") + hr
  min = ((min < 10) ? "0" : "") + min
  sec = ((sec < 10) ? "0" : "") + sec
  document.clock.digits.value = hr + ":" + min + ":" + sec
  setTimeout("clock()", 1000)
  }

This format is more compact but it really doesn't run any faster. So it is just a different way of doing the same thing.

The syntax for the condition expression is

 variable = (condition) ? val1 : val2

The way this works is that if the condition is true then the variable is set to val1 but if the condition is false then the variable is set to val2. For example in our modified clock script, if min < 10 then the variable min is set to "0" + min else min is set to "" + min.

You will also see other variations of these two methods of doing the clock script. Use whichever one you feel the most comfortable with.


Greeting Based on Time of Day

Here is the function that I used in Lesson 1 to greet you. Take a look at it now and I bet it will look pretty simple. All the function does is get today's date, determine the hour and then use a couple of if statements to determine the proper greeting. The greeting is returned by the function to be used in a document.write() method.

 function getGreeting(){
   var curDateTime = new Date()
   var curHour = curDateTime.getHours()
   var greeting = "Good Evening"
   if (curHour < 12  && curHour >= 0)
     greeting = "Good Morning"
   if (curHour >=12 && curHour < 18)
     greeting = "Good Afternoon"
   return greeting
   }


Date Arithmetic

Date arithmetic is relatively easy if you remember that time in JavaScript is measured in milliseconds. Use the date method getTime() to determine the number of milliseconds that have elapsed since the magic date of January 1, 1970. Use the setTime() method to establish a date you have calculated in term of milliseconds.

Danny Goodman, author of the JavaScript bible recommends that you set up some variables that build on each other to make it easier to do Date Arithmetic. Here is the variable setup that he recommends:

 var oneMinute = 60 * 1000  // milliseconds in a minute
 var oneHour = oneMinute * 60
 var oneDay = oneHour * 24
 var oneWeek = oneDay * 7

Once this is done you can calculate a future date based on today's date using these variables. For example, here is how you would find the date 5 weeks from now.

 var today = new Date()
 var dateInMS = today.getTime() + oneWeek * 5
 var targetDate = new Date(dateInMS)
Now you can use the other methods of the date object to print this date out, find out what day of the week it occurs on and etc.

Here's another way that you can determine a future date. Suppose that your birthday was on February 5 of this year and you would like to know what day it will be on next year. Here's how you can do this.

 var myBirthday = new Date("2/5/1999")
 myBirthday.setYear("2000")
 dayOfMyNextBirthday = myBirthday.getDay()

Yes, you are right, I could have just set the date to 2/5/2000 to start with and then determined the day of the week. There will be times when you want to do it the way I did however. For instance, you might have already established a date object and then just want to add a year to it. Don't forget that our results will be a number that you must convert to an actual day of the week using the technique we learned in this week's first lesson.


A GMT Clock

Using a little date arithmetic, we can convert our 24 hour clock into a one that shows Greenwich Mean Time.

  GMT Time: 

Here's the function that I used for the GMT clock. There are only two new lines needed to make the clock display Greenwich Mean Time. First we calculate the number of milliseconds that represents the current GMT time. We do this by using the getTime() method to determine the milliseconds for our local time. We then get our offset from GMT by using the getTimezoneOffset() method. Since this value is in seconds we have to multiply it by 60000 to convert it to milliseconds and then add the two numbers together to get the current GMT time in milliseconds. We then use this value to create a new object for our GMT and assign it to the variable gmtTime. That's all there is to it. I did change some of the variable names and the name of the form object to make this clock work on the same page as our 24 hour clock.

 function GMTclock(){
   var time = new Date()
   var gmtMS = time.getTime() 
              + (time.getTimezoneOffset() * 60000)
   var gmtTime =  new Date(gmtMS)
   var hr = gmtTime.getHours()
   var min = gmtTime.getMinutes()
   var sec = gmtTime.getSeconds()
   if(hr < 10){
     hr = " " + hr
     }
   if(min < 10){
     min = "0" + min
     }
   if(sec < 10){
     sec = "0" + sec
     } 
   document.gmt.digits.value= hr + ":" + min + ":" + sec
   setTimeout("GMTclock()", 1000)
   }


Assignment

Note: See Appendix 4 to learn how to make your date scripts Y2K compatible.

  1. Set up a 24 hour clock like the one we described here on a web page to make sure the you understand how it is done.
    Solution   Source

  2. Make a clock that will display the time in a 12 hour format. Have the time displayed on a button instead of a text box. Design your page so that when someone clicks on the button, an alert box is displayed with today's date in it.
    Solution   Source



[ Top of Page  |  Contents ]