Javascript Lesson 7

Foreword

In this lesson, you will learn how to make clocks and you will also see some Date arithmetic.

7.1 Your First Clock

This is the script to display the time:

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

The problem with using this script for 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 hour = time.getHours()
var minutes = time.getMinutes()
var seconds = time.getSeconds()
if(hour < 10){
  hour = " " + hour
  }
if(minutes < 10){
  minutes = "0" + minutes
  }
if(seconds < 10){
  seconds = "0" + seconds
  } 
document.write(hour + ":" + minutes + ":" + seconds)
//-->
</script>

Notice that there also is a blank space in front of the hour when it is below 10. Now you will ad a function to the script that will display the results in a form text box. You will have to use the setTimeout() function from Lesson 5 to call the function every second to display the time. Remember that the second parameter of the setTimeout() function determines the amount of time in milliseconds that goes by before the function specified in the first parameter is called. This means that you will have to use 1000 as second parameter.
Beneeth is the completed clock() function that should be put in the Head section of the document:

<script language="JavaScript">
<!--
function clock(){
 var time = new Date()
 var hour = time.getHours()
 var minutes = time.getMinutes()
 var seconds = time.getSeconds()
 if(hour < 10){
   hour = " " + hour
   }
 if(minutes < 10){
   minutes = "0" + minutes
   }
 if(seconds < 10){
   seconds = "0" + seconds
   } 
  document.clock.display.value = hour + ":" + minutes + ":" + seconds
  setTimeout("clock()", 1000)
  }
//-->
</script>

Here is the code for the form that is used in the Body section of the document to display the results from the clock() function:

<form name="clock">
<input type="text" name="display" size="8" value="Loading...">
</form>

The last thing you should do to finish the clock is putting the following code inside the Body tag:

onLoad = "clock()"

And this is how the clock will look like:

This clock displays in the 24-hour format. If you want to make a 12 hour clock, you will need to add some 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.

7.2 Date Arithmetic

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

To make Date Arithmetic easier you should set up some variables that build on each other.
The variable setup:

var minute = 60 * 1000
var hour = oneMinute * 60
var day = oneHour * 24
var week = oneDay * 7

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

var minute = 60 * 1000
var hour = oneMinute * 60
var day = oneHour * 24
var week = oneDay * 7
var time = new Date()
var timeMilliSec = time.getTime() + week * 2
var target = new Date(timeMilliSec)

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 is another way to determine a future date. Imagine that your birthday was on December 2 of this year and you would like to know what day it will be on next year:

var birthday = new Date("12/2/2006")
birthday.setYear("2007")
dayOfNextBirthday = birthday.getDay()

Of course, you could have just set the date to 12/2/2007 to start with and then determined the day of the week.
But when you start working with a variable date or the input from someone else, this method will be verry usefull.

7.3 GMT Clock

Using a little date arithmetic, you will be able to convert your 24 hour clock into one that shows Greenwich Mean Time. There are only two new lines of code needed to make the clock display Greenwich Mean Time.
First you calculate the number of milliseconds that represents the current GMT time. You do this by using the getTime() method to determine the milliseconds for your local time and then get the timezone offset by using the getTimezoneOffset() method.
Since this value is in seconds, you will have to multiply it by 60000 to convert it to milliseconds and then add the two numbers together to get the current Greenwich Mean Time in milliseconds.
Next, you will have to use this value to create a new object for your GMT and assign it to the variable gmtTime.
This is the full code to display Greenwich Mean Time:

For the Head part of the document:

<script language="JavaScript">
<!--
function gmtClock(){
 var time = new Date()
 var gmtMilliSec = time.getTime() + (time.getTimezoneOffset() * 60000)
 var gmtTime = new Date(gmtMilliSec)
 var hour = gmtTime.getHours()
 var minutes = gmtTime.getMinutes()
 var seconds = gmtTime.getSeconds()
 if(hour < 10){
  hour = " " + hour
  }
 if(minutes < 10){
  minutes = "0" + minutes
  }
 if(seconds < 10){
  seconds = "0" + seconds
  } 
 document.gmtClock.display.value = hour + ":" + minutes + ":" + seconds
 setTimeout("gmtClock()", 1000)
 }
//-->
</script>

For the Body section:

<form name="gmtClock">
<input type="text" name="display" size="8" value="Loading...">
</form>

And again, you should not forget to put the following code inside the Body tag:

onLoad = "gmtClock()"

And this is how the GMT clock will look like:

7.4 Exercices

  • Try to make a 12-hour clock by using if-statements for am and pm (Make sure that the hours cannot go past 12)
  • Make a greeting script that will write "Good Morning", "Good Afternoon" or "Good Evening" based on the time.
  • Make a 24-hour clock display on a button and show an alert box that displays the date when someone clicks on it.
Home | Code | Learn
© 2007-2008 ProgLogic, all rights reserved. | ProgLogic.com is created by Stijn Strickx. | e-mail