JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

World Time

The concept of "now" means the same point in time everywhere in the world. However, when that point in time is represented by numbers, those numbers differ depending on where you are. What is needed is a standard number to represent that moment in time. This is achieved through Coordinated Universal Time (UTC), which is an international basis of civil and scientific time and was implemented in 1964. It was previously known as GMT (Greenwich Mean Time), and indeed at the time 0:00 UTC, it is midnight in Greenwich, London.

The following table shows the local times around the world at 0:00 UTC time.

San Francisco

New York (EST)

Greenwich, London

Berlin, Germany

Tokyo, Japan

4:00 pm

7:00 pm

0:00 midnight

1:00 am

9:00 am

Note that the times given are winter times—no daylight saving hours are taken into account.

The support for UTC in JavaScript comes from a number of methods of the Date object that are similar to those we have already seen. For each of the "set date" and "get date" type methods we've seen so far, there is a UTC equivalent. For example, whereas setHours() sets the local hour in a Date object, setUTCHours() does the same thing for UTC time. We'll be looking at these methods in more detail in the next section.

In addition, there are three more methods of the Date object that involve world time.

We have the methods toUTCString() and toLocaleString(), which return the date and time stored in the Date object as a string based on either UTC or local time. Newer browsers, IE 5.5+ and NN 6+, also have the additional methods: toLocaleTimeString(); toTimeString(); toLocaleDateString(); and toDateString().

If we simply want to find out the difference in minutes between the current locale's time and that of UTC time, we can use the getTimezoneOffset() method. If the time zone is behind UTC, such as in the United States, it will return a positive number. If the time zone is ahead, such as in Australia or Japan, it will return a negative number.

Try It Out – The World Time Method of the Date Object

In the following code we use the toLocaleString(), toUTCString(), getTimezoneOffset(), toLocaleTimeString(), toTimeString(), toLocaleDateString(), and toDateString() methods and write their values out to the page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>example</title>
<script language="JavaScript" type="text/javascript">
   var localTime = new Date();
</script>
</head>
<body>
<h4>
   UTC Time is
   <script language="JavaScript" type="text/javascript">
    
      document.write(localTime.toUTCString());
   </script>
</h4>
<h4>
   Local Time is
   <script language="JavaScript" type="text/javascript">
      document.write(localTime.toLocaleString());
   </script>
</h4>
<h4>
   Time Zone Offset is
   <script language="JavaScript" type="text/javascript">
      document.write(localTime.getTimezoneOffset());
</script>
</h4>
    
<h4>
Using toLocalTimeString() gives:
<script language="JavaScript" type="text/javascript">
if (localTime.toLocaleTimeString)
{
  document.write(localTime.toLocaleTimeString())
}
</script>
</h4>
    
    
<h4>
Using toTimeString() gives:
<script language="JavaScript" type="text/javascript">
if (localTime.toTimeString)
{
  document.write(localTime.toTimeString() )
}
</script>
</h4>
    
    
<h4>
Using toLocaleDateString() gives:
<script language="JavaScript" type="text/javascript">
if (localTime.toLocaleDateString)
{
  document.write(localTime.toLocaleDateString())
}
</script>
</h4>
    
<h4>
Using toDateString() gives:
<script language="JavaScript" type="text/javascript">
if (localTime.toDateString)
{
  document.write(localTime.toDateString())
}
</script>
</h4>
    
    
</body>
</html>

Save this as timetest.htm and load it into your browser. What you see will, of course, depend on which time zone your computer is set to, but you should see something like that shown in Figure 9-1.

Click To expand
Figure 9-1

Here I have my computer's time set to the time 19:10:43pm on 16th October 2004 in America's Eastern Standard Time (for example, New York).

Note that on Netscape 4.0+ browsers, it will actually have GMT at the end of the first line rather than UTC. Also note that in NN 4 and IE 4 or 5, the code that uses the toLocaleTimeString(), toTimeString(), toLocaleDateString(), and toDateString() methods are not supported by these browsers, and therefore nothing will be displayed on those lines. The object-checking if statements we used allow the page to be loaded into these browsers with no errors.

How It Works

So how does this work? In the script block at the top of the page, we have just this one line:

var localTime = new Date();

This creates a new Date object and initializes it to the current date and time based on the client computer's clock. (Note that in fact the Date object simply stores the number of milliseconds between the date and time on your computer's clock and midnight UTC time on the 1st of January 1970.)

Within the body of the page we have seven more script blocks that use the three world time methods we looked at earlier. Note that some of them are enclosed in an if statement, for example

if (localTime.toLocaleTimeString)
{
  document.write(localTime.toLocaleTimeString())
}

This checks to see if the browser supports that method and only makes use of it if it does. Older browsers don't support all of the date/time methods so doing this prevents ugly errors.

In the following line

document.write(localTime.toUTCString());

we write the string returned by the toUTCString() method to the page. This converts the date and time stored inside the localTime Date object to the equivalent UTC date and time.

Then the line

document.write(localTime.toLocaleString());

returns a string with the local date and time value. Since this time is just based on the user's computer's clock, the string returned by this method will also adjust for daylight saving time (as long as the clock adjusts for daylight saving time).

Next, the code

document.write(localTime.getTimezoneOffset());

writes out the difference, in minutes, between the local time zone's time and that of UTC time.

You may notice in Figure 9-2 that the difference between New York time and UTC time is written to be 240 minutes, or 4 hours. Yet, in the previous table, we said that New York is 5 hours behind UTC time. So what is happening?

Click To expand
Figure 9-2

Well, actually in New York on October 16th, daylight saving hours are in use. During the summer when it's 8:00 p.m. in New York and 0:00 UTC time, it is 7:00 p.m. in New York and 0:00 UTC time in the winter. Therefore, in the summer the getTimezoneOffset() method will return 240, while in the winter the getTimezoneOffset() method will return 300.

To illustrate this, compare Figure 9-1 to Figure 9-2, where I have advanced the date on my computer's clock forward by two months.

The next two methods are toLocaleTimeString() and toTimeString(), as follows:

<h4>
Using toLocalTimeString() gives:
<script language="JavaScript" type="text/javascript">
document.write(localTime.toLocaleTimeString())
</script>
</h4>
    
    
<h4>
Using toTimeString() gives:
<script language="JavaScript" type="text/javascript">
 document.write(localTime.toTimeString() )
</script>
</h4>

These are NN 6+- and IE 5.5+-only methods. They display just the time part of the date/time held in the Date object. The toLocaleTimeString() method displays the time as specified by the user on his computer. The second method displays the time but also gives an indication of time zone (in the example, EST for Eastern Standard Time in America).

The final two methods display the date part of the date/time. The toLocaleDateString() displays the date in the format the user has specified on his computer. On Windows operating systems, this is set in the regional settings of the PC's Control Panel. However because it relies on the user's PC setup, the look of the date will vary from computer to computer. The toDateString() method displays the current date contained in the PC date in a standard format.

Of course, this example relies on the fact that the user's computer's clock is set correctly, not something we can be 100 percent sure of—it's amazing how many users have their local time zone settings set completely wrong.

Setting and Getting a Date Object's UTC Date and Time

When we create a new Date object, we can either initialize it with a value or let JavaScript set it to the current date and time. Either way, JavaScript assumes we are setting the local time values. If we want to specify UTC time, we need to use the setUTC type methods, such as setUTCHours().

The following are the seven methods for setting UTC date and time:

  • setUTCDate()

  • setUTCFullYear()

  • setUTCHours()

  • setUTCMilliseconds()

  • setUTCMinutes()

  • setUTCMonth()

  • setUTCSeconds()

The names pretty much give away exactly what each of the methods does, so let's launch straight into a simple example, which sets the UTC time. These UTC methods were introduced in IE 4.0 and NN 4.06, so you will need one of these or a later version to run the code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<script language=JavaScript type="text/javascript">
var myDate = new Date();
myDate.setUTCHours(12);
myDate.setUTCMinutes(0);
myDate.setUTCSeconds(0);
document.write("<h3>" + myDate.toUTCString() + "</h3>")
document.write("<h3>" + myDate.toLocaleString() + "</h3>")
</script>
</body>
</html>

Save this as settimetest.htm. When you load it in your browser, you should see something like that shown in Figure 9-3 in your web page, though the actual date will depend on the current date and where you are in the world.

Click To expand
Figure 9-3

You might want to change your computer's time zone and time of year to see how it varies in different regions and with daylight saving changes. For example, although I'm in the U.K., I have changed the settings on my computer for this example to Eastern Standard Time in the U.S.A. In Windows you can make the changes by opening the Control Panel and then double-clicking the Date/Time icon.

So how does this example work? We declare a variable myDate and set it to a new Date object. Because we haven't initialized the Date object to any value, it will contain the local current date and time.

Then using the setUTC methods, we set the hours, minutes, and seconds so that the time will be 12:00:00 (midday, not midnight) UTC time.

Now, when we write out the value of myDate as a UTC string, we get 12:00:00 and today's date. When we write out the value of the Date object as a local string, we get today's date and a time that is the UTC time 12:00:00 converted to the equivalent local time. The local values you'll see will, of course, depend on your time zone. For example, New Yorkers will see 08:00:00 during the summertime and 07:00 during the wintertime due to daylight savings. In the U.K. in the winter, you'll see 12:00:00, but in the summer you'll see 13:00:00.

For getting UTC dates and times, we have the same functions as used for setting UTC dates and times, except that this time, for example, it's getUTCHours() not setUTCHours().

  • getUTCDate()

  • getUTCDay()

  • getUTCFullYear()

  • getUTCHours()

  • getUTCMilliseconds()

  • getUTCMinutes()

  • getUTCMonth()

  • getUTCSeconds()

Notice that this time there is an additional method, getUTCDay(). This works in the same way as the getDay() method and returns the day of the week as a number, from 0 for Sunday to 6 for Saturday. Because the day of the week is decided by the day of the month, the month, and the year, there is no setUTCDay() method.

Before we move on to look at timers, let's use our newly gained knowledge of the Date object and world time to create a world time converter. Later in this chapter, when we've learned how to use timers, we'll update the example to produce a world time clock. Note that this example only works with IE 4.0+ and NN 4.06+. It won't work with IE 3 or NN 4.05 and earlier.

Try It Out – World Time Converter (Part I)

The world time converter consists of two pages. The first is a frameset page, and the second is the page where the time conversion form exists. Let's start by creating the frameset page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
</head>
<frameset cols="250,*" frameborder="0">
   <frame src="worldtimeconverter.htm" name=formFrame>
   <frame src="about:blank" name=resultsFrame>
</frameset>
</html>

This simply divides the page into two frames. However, by setting the border between the frames to 0, we can make it look like just a single page. Save this frameset page as WorldTimeConverterFrameset.htm.

The left frame will contain the form in which the user can select the city that she wants the time of, and the right frame will show the results of the conversion. The right frame will be written using code, so there is no page to create for that.

We'll now create the left frame's page.

<html>
<head>
<script language=javascript>
var timeDiff;
var selectedCity;
var daylightSavingAdjust = 0;
function updateTimeZone()
{
   var lstCity = document.form1.lstCity;
   timeDiff = lstCity.options[lstCity.selectedIndex].value;
   selectedCity = lstCity.options[lstCity.selectedIndex].text;
   updateTime();
}
function getTimeString(dateObject)
{
   var timeString;
   var hours = dateObject.getHours();
   if (hours < 10)
      hours = "0" + hours;
   var minutes = dateObject.getMinutes();
   if (minutes < 10)
      minutes = "0" + minutes;
   var seconds = dateObject.getSeconds()
   if (seconds < 10)
      seconds = "0" + seconds;
   timeString = hours + ":" + minutes + ":" + seconds;
   return timeString;
}
function updateTime()
{
   var nowTime = new Date();
   var resultsFrame = window.top.resultsFrame.document;
   resultsFrame.open()
   resultsFrame.write("Local Time is " + getTimeString(nowTime) + "<br>");

   nowTime.setMinutes(nowTime.getMinutes() + nowTime.getTimezoneOffset() +
      parseInt(timeDiff) + daylightSavingAdjust);
   resultsFrame.write(selectedCity + " time is " + getTimeString(nowTime));
   resultsFrame.close();
}
function chkDaylightSaving_onclick()
{
   if (document.form1.chkDaylightSaving.checked)
   {
      daylightSavingAdjust = 60;
   }
   else
   {
      daylightSavingAdjust = 0;
   }
   updateTime();
}
</script>
</head>
<body onload="updateTimeZone()">
<form name=form1>
<select size=5 name=lstCity language=JavaScript onchange="updateTimeZone();">
<option value=60 selected>Berlin
<option value=330>Bombay
<option value=0>London
<option value=180>Moscow
<option value=-300>New York (EST)
<option value=60>Paris
<option value=-480>San Francisco (PST)
<option value=600>Sydney
</select>
<p>
It's summer time in the selected city
and its country adjusts for summertime daylight saving
<input type="checkbox" name=chkDaylightSaving language=JavaScript
   onclick="return chkDaylightSaving_onclick()">
</p>
</form>
</body>
</html>

Save this page as WorldTimeConverter.htm. Then load the WorldTimeConverterFrameset.htm page into your browser. (Remember that an NN 4.06+ or an IE 4.0+ browser is needed.)

The form layout looks something like that shown in Figure 9-4. Whenever the user clicks on a city in the list, the user's local time and the equivalent time in the selected city are shown. In the example shown in Figure 9-4, my local region is set to Eastern Standard Time in the U.S.A. (for a city such as New York), and I've clicked on Berlin in the list and checked the box for summertime daylight saving in Berlin.

Click To expand
Figure 9-4

It's worth pointing out that this is an example and not a totally foolproof one due to the problems of daylight saving. Some countries don't have daylight saving, others do at fixed times of year, and yet others do but at varying times of the year. This makes it virtually impossible to accurately predict when a country will have its daylight saving period. We have tried to solve this problem by adding a checkbox for the user to click if the city he chooses from the list is using daylight saving hours (which we assume will put the time in the city forward by one hour).

In addition, don't forget that some users may not even have their regional settings set correctly—there's no easy way around this problem.

How It Works

Before we look at WorldTimeConverter.htm, let's just pick up on one point in the frameset-defining page WorldTimeConverterFrameset.htm.

<frame src="about:blank" name=resultsFrame>

Notice how we have set the src attribute of the right-hand frame to "about:blank". This is necessary for some browsers, mainly Netscape—without it, document.write() will sometimes fail because there is no page loaded to write to. Note that as it stands, this example doesn't work with Opera 7. To make it work we simply need to create a blank HTML page and load that into the results frame.

Now we'll turn to the page WorldTimeConverter.htm where most of the action is. In the body of the page is a form in which we've defined a list box using a <select> element.

<select size=5 name=lstCity language=JavaScript onchange="updateTimeZone();">
<option value=60 selected>Berlin
<option value=330>Bombay
<option value=0>London
<option value=180>Moscow
<option value=-300>New York (EST)
<option value=60>Paris
<option value=-480>San Francisco (PST)
<option value=600>Sydney
</select>

Each of the options displays the city's name in the list box and has its value set to the difference in minutes between that city's time zone (in winter) and UTC. So London, which is the same as UTC time, has a value of 0. Paris, which is an hour ahead of UTC, has a value of 60 (that is, 60 minutes). New York, which is 5 hours behind UTC time, has a value of -300.

You'll see that we have captured the onchange event of the <select> element and connected it to the function updateTimeZone() defined in a script block in the head of the page. This function involves three global variables defined at the top of the script block.

var timeDiff;
var selectedCity;
var daylightSavingAdjust = 0;

The function updateTimeZone() updates two of these, setting the variable timeDiff to the value of the list's selected option (that is, the time difference between the selected city and UTC time) and the variable selectedCity to the text shown for the selected option (that is, the selected city).

function updateTimeZone()
{
   var lstCity = document.form1.lstCity;
   timeDiff = lstCity.options[lstCity.selectedIndex].value;
   selectedCity = lstCity.options[lstCity.selectedIndex].text;

In the final part of the function updateTimeZone(), the function updateTime() is called as shown in the following:

   updateTime();
}

Before we go on to look at this function, we return to the final part of the form on the page. This is a checkbox, which is clicked by the user if the city she has chosen from the select list is in the summertime of a country that uses daylight saving hours.

<input type="checkbox" name=chkDaylightSaving language=JavaScript
   onclick="return chkDaylightSaving_onclick()">

As you can see, this checkbox's onclick event is connected to another function, chkDaylightSaving_onclick().

function chkDaylightSaving_onclick()
{
   if (document.form1.chkDaylightSaving.checked)
   {
      daylightSavingAdjust = 60;
   }
   else
   {
      daylightSavingAdjust = 0;
   }

Inside the if statement, the code accesses the checkbox's checked property, which returns true if it is checked and false otherwise. If it has been checked, we set the global variable daylightSavingAdjust to 60 for summertime daylight saving; otherwise it's set to 0.

   updateTime();
}

At the end of this function (as at the end of the function updateTimeZone() we saw earlier), the updateTime() function is called. We'll look at that next.

In the function updateTime(), we write the current local time and the equivalent time in the selected city to the right-hand frame, named resultsFrame, which we defined in the frameset page.

We start at the top of the function by creating a new Date object, which is stored in the variable nowTime. The Date object will be initialized to the current local time.

function updateTime()
{
   var nowTime = new Date();

Next, to make our code more compact and easier to understand, we define a variable resultsFrame, which will reference the document object contained in the resultsFrame window.

   var resultsFrame = window.top.resultsFrame.document;

With our reference to the resultsFrame document, we then open the document to write to it. Doing this will clear anything currently in the document and provide a nice blank document to write our HTML into. The first thing we write is the local time based on the new Date object we just created. However, we want the time to be nicely formatted as hours:minutes:seconds, so we've written another function, getTimeString(), which does this for us. We'll look at that shortly.

   resultsFrame.open()
   resultsFrame.write("Local Time is " + getTimeString(nowTime) + "<br>");

Having written the current time to our resultsFrame, we now need to calculate what the time would be in the selected city before also writing that to the resultsFrame.

We saw in Chapter 4 that if we set the value of a Date object's individual parts (such as hours, minutes, and seconds) to a value beyond their normal range, JavaScript assumes you want to adjust the date, hours, or minutes to take account of this. For example, if we set the hours to 36, JavaScript simply sets the hours to 12 and adds one day to the date stored inside the Date object. We use this to our benefit in the following line:

   nowTime.setMinutes(nowTime.getMinutes() + nowTime.getTimezoneOffset() +
      parseInt(timeDiff) + daylightSavingAdjust);

Let's break this line down to see how it works. Suppose that we're in New York, with the local summer time of 5:11, and we want to know what time it would be in Berlin. How does our line of code calculate this?

First we get the minutes of the current local time; it's 5:11, so nowTime.getMinutes() returns 11.

Then we get the difference, in minutes, between the user's local time and UTC time using nowTime.getTimezoneOffset(). If we are in New York, which is different from UTC time by 4 hours during the summer, this is 240 minutes.

Then we get the integer value of the time difference between the standard winter time in the selected city and UTC time, which is stored in the variable timeDiff. We've used parseInt() here because it's one of the few situations where JavaScript gets confused and assumes we want to join two strings together rather than treat the value as a number and add it together. Remember that we got timeDiff from an HTML element's value, and an HTML element's values are strings, even when they hold characters that are digits. Since we want the time in Berlin, which is 60 minutes different from UTC time, this will be 60.

Finally, we add the value of daylightSavingsAdjust. This variable is set in the function chkdaylightsaving_onclick(), which we discussed earlier. Since we are in the summer and Berlin uses daylight saving hours, this value is 60.

So we have the following:

11 + 240 + 60 + 60 = 371

Therefore nowTime.setMinutes() is setting the minutes to 371. Clearly, there's no such thing as 371 minutes past the hour, so instead JavaScript assumes we mean 6 hours and 11 minutes after 5:00, that is 11:11—the time in Berlin that we wanted.

Finally the updateTime() function writes the results to the resultsFrame, then closes off the document writing.

   resultsFrame.write(selectedCity + " time is " + getTimeString(nowTime));
   resultsFrame.close();
}

In the updateTime() function, we saw that it utilizes the function getTimeString() to format the time string. Let's look at that function now. This function is passed a Date object as a parameter and uses that to create a string with the format hours:minutes:seconds.

function getTimeString(dateObject)
{
   var timeString;
   var hours = dateObject.getHours();
   if (hours < 10)
      hours = "0" + hours;
   var minutes = dateObject.getMinutes();
   if (minutes < 10)
      minutes = "0" + minutes;
   var seconds = dateObject.getSeconds()
   if (seconds < 10)
      seconds = "0" + seconds;
   timeString = hours + ":" + minutes + ":" + seconds;
   return timeString;
}

Why do we need this function? Well, we can't just use

getHours() + ":" + getMinutes() + ":" + getSeconds()

because that won't take care of those times when any of the three results of these functions is less than 10. For example, 1 minute past 12 would look like 12:1:00 rather than 12:01:00.

The function therefore gets the values for hours, minutes, and seconds and checks each to see if they are below 10. If they are below 10, a zero is added to the front of the string. When all the values have been retrieved, they are concatenated together in the variable timeString before being returned to the calling function.

In the next section we're going to look at how, by adding a timer, we can make the displayed time update every second like a clock.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©