Previous Page
Next Page

Displaying Dates by Time Zone

By default, the dates and times that are displayed are those on the user's machine (assuming that they are set correctly). If you want to display a date somewhere else, you need to calculate it based on UTC, Coordinated Universal Time. UTC is essentially a different name for Greenwich Mean Time (GMT); UTC also goes under the names "universal time" (UT) and "world time." Script 13.4 shows the HTML for the page; Script 13.5, with the JavaScript, shows you how to calculate dates in other time zones.

Script 13.4. The HTML for the time zone script uses classes to tag the different offices with the time zone for that office.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Time Zones</title>
     <script language="Javascript" type="text/  javascript" src="script04.js">
     </script>
</head>
<body bgcolor="#FFFFFF">
     <h3>Our office hours are 9:00 am to 5:00 pm, Monday through Friday, at each of our 
locations. It is now</h3><ul>
     <li><span class="tz-8"> </span> in San Francisco</li>
     <li><span class="tz-5"> </span> in New York</li>
     <li><span class="tz-0"> </span> in London</li>
     <li><span class="tz+7"> </span> in Hong Kong</li></ul>
</body>
</html>

Script 13.5. You can adapt this script to display any time zone you wish.

window.onload = initDate;

function initDate() {
     var allTags = document.getElementsByTagName("*");

     for (var i=0;i<allTags.length; i++) {
        if (allTags[i].className.indexOf("tz")==0) {
           showTheTime(allTags[i],allTags[i].className.substring(2));
        }
     }
}

function showTheTime(currElem,tzOffset) {
     var dayName = new Array ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"
,"Saturday");

     var thatTZ = new Date();
     var dateStr = thatTZ.toUTCString();

     dateStr = dateStr.substr(0,dateStr.length - 3);
     thatTZ.setTime(Date.parse(dateStr));
     thatTZ.setHours(thatTZ.getHours() + parseInt(tzOffset));

     currElem.innerHTML = showTheHours(thatTZ.getHours()) + showZeroFilled(thatTZ.
getMinutes()) + showAmPm(thatTZ.getHours()) + dayName[thatTZ.getDay()];

     function showTheHours(theHour) {
        if (theHour == 0) {
           return (12);
        }
        if (theHour < 13) {
           return (theHour);
        }
        return (theHour-12);
     }

     function showZeroFilled(inValue) {
        if (inValue > 9) {
           return ":" + inValue;
        }
        return ":0" + inValue;
     }

     function showAmPm(thatTime) {
        if (thatTime < 12) {
           return (" AM ");
        }
        return (" PM ");
     }
}

To display dates by time zone:

1.
function initDate() {
  var allTags = document. getElementsByTagName("*");



Begin the initDate() function, then create the allTags variable. The command document.getElementsByTagName("*") is a handy trickthat asterisk tells JavaScript to return an array containing every tag on the page. Then, we can just loop through it looking for things of interest.

2.
for (var i=0;i<allTags.length; i++) {
  if (allTags[i].className. indexOf("tz")==0){
    showTheTime(allTags[i], allTags[i].className. substring(2));
  }
}



We begin a loop so we can walk through the page elements, represented by allTags. The allTags[i].className.indexOf("tz")==0 bit just means, "does the ith tag have an attribute class that starts with "tz"if so, call showTheTime()."

The showTheTime() function is passed two parameters: first, the ith tag element, and second, the part of the class attribute (seen in Script 13.4) that is after the "tz", represented by substring(2). Yes, we could figure out the second part from the first, but why bother? It makes the showTheTime() function much simpler, as that second parameter turns into the time zone offset.

3.
function showTheTime(currElem, tzOffset) {



This function takes in the two parameters that were passed to showTheTime() in the previous step. Inside the function, they'll be called currElem and tzOffset, respectively.

4.
var thatTZ = new Date();
var dateStr = thatTZ.toUTCString();



We create a new date variable, thatTZ. The next line turns that date and time (based on UT) into a string (see Table 13.1 at the end of the chapter), saving the result in dateStr.

Table 13.1. Date Methods

Method

Description

ReturnedValues

Supporting Browsers

geTDate()

The day of the month

131

JavaScript 1.0

getUTCDate()

  

JavaScript 1.2

getday()

The integer value of the day of the week

06

JavaScript 1.0

getUTCDay()

  

JavaScript 1.2

getFullYear()

The full four-digit year

1900+

JavaScript 1.2

getUTCFullYear()

   

getHours()

The integer hour of the day

023

JavaScript 1.0

getUTCHours()

  

JavaScript 1.2

getMilliseconds()

The number of milliseconds since the last second

0999

JavaScript 1.2

getUTCMilliseconds()

   

getMinutes()

The number of minutes since the last hour

059

JavaScript 1.0

getUTCMinutes()

  

JavaScript 1.2

getMonth()

The month of the year

011

JavaScript 1.0

getUTCMonth()

  

JavaScript 1.2

getSeconds()

The number of seconds since the last minute

059

JavaScript 1.0

getUTCSeconds()

  

JavaScript 1.2

getTime()

The number of milliseconds since midnight 1 January 1970

 

JavaScript 1.0

getTimezoneOffset()

The difference between local time and GMT in minutes

01439

JavaScript 1.0

getYear()

The year field of the date

099 for the years 19001999, four-digit year thereafter

JavaScript 1.0

parse()

Given a date/time string, return the number of milliseconds since midnight 1 January 1970

 

JavaScript 1.0

setDate()

Set the day, given a number between 131

Date in milliseconds (as of JavaScript 1.2)

JavaScript 1.0

setUTCDate()

  

JavaScript 1.2

setFullYear()

Set the year, given a four-digit year

Date in milliseconds

JavaScript 1.2

setUTCFullYear()

   

setHours()

Set the hour, given a number between 023

Date in milliseconds (as of JavaScript 1.2)

JavaScript 1.0

setUTCHours()

  

JavaScript 1.2

setMilliseconds()

Set the milliseconds, given a number between 0999

Date in milliseconds

JavaScript 1.2

setUTCMilliseconds()

   

setMinutes()

Set the minutes, given a number between 059

Date in milliseconds (as of JavaScript 1.2)

JavaScript 1.0

setUTCMinutes()

  

JavaScript 1.2

setMonth()

Set the month, given a number between 011

Date in milliseconds (as of JavaScript 1.2)

JavaScript 1.0

setUTCMonth()

  

JavaScript 1.2

setSeconds()

Set the seconds, given a number between 059

Date in milliseconds (as of JavaScript 1.2)

JavaScript 1.0

setUTCSeconds()

  

JavaScript 1.2

setTime()

Set a date, given the number of milliseconds since 1 January 1970

Date in milliseconds

JavaScript 1.0

setYear()

Set the year, given either a two- or four-digit value

Date in milliseconds (as of JavaScript 1.2)

JavaScript 1.0

toGMTString()

The GMT date and time in string format

day dd mm yyyy hh:mm:ss GMT

JavaScript 1.0

toUTCString()

  

JavaScript 1.2

toLocaleString()

The local date and time in string format

Varies based on OS, locale, and browser

JavaScript 1.0

toString()

The local date and time in string format

Varies based on OS and browser

JavaScript 1.0

UTC()

Given a date in year, month, day (and optional hours, minutes, seconds, and milliseconds) format, return the number of milliseconds since 1 January 1970

Date in milliseconds

JavaScript 1.0

valueOf()

The number of milliseconds since midnight 1 January 1970

Date in milliseconds

JavaScript 1.2


5.
dateStr = dateStr.substr (0,dateStr.length - 3);



What we're trying to do in this section is reset thatTZ to be based on UT instead of local time, so that we can then add the passed offset for the desired result. Unfortunately, JavaScript doesn't make this simple. We now have UT time in string format, but if we just try to reset the time based on it, it'll outsmart us, knowing that we really want local time. What we need to do is take the string version of the date and time and strip off the last three characters, which are UTC.

6.
thatTZ.setTime(Date.parse(dateStr));



Once we've stripped off the last three characters, we can use the parse method to turn the date into milliseconds and then the setTime method to set thatTZ to our desired time.

7.
thatTZ.setHours(thatTZ.getHours() + parseInt(tzOffset));



Now that we've finally got the UT date stored, we need to add the passed number of hours that our desired time is off UT. As the time zone can be anywhere from +12 to -12, the time zone that was passed in can be anything from "-12" to "+12". We use parseInt() to turn that string into a number from -12 to 12, and we then add it to the current UT time. The result gives us our desired value: the correct date and time in that time zone.

8.
currElem.innerHTML = showTheHours (thatTZ.getHours()) + showZeroFilled(thatTZ. getMinutes
()) + showAmPm (thatTZ.getHours()) + dayName[thatTZ.getDay()];



This looks scary, but all it is doing is building the time value that goes into the document by concatenating the result from all of the other functions and then setting the innerHTML property of currElem, thereby putting the result of the calculation into the document. The final result is shown in Figure 13.4.

Figure 13.4. The script calculates the time in each office, based on its time zone.


The next three functions, showTheHours(), showZeroFilled(), and showAmPm() are within the showTheTime() function so that they can share variables. As it turns out, they don't in this task, but they will in the next.

9.
function showTheHours(theHour) {
   if (theHour == 0) {
      return (12);
   }



First, set up a function called showTheHours, containing the variable theHour. Then, if theHour is zero, return the result 12 (meaning the hour is 12 A.M.); otherwise continue with the script.

10.
if (theHour < 13) {
   return (theHour);
}
return (theHour-12);



If the result of the hour portion of the time is less than 13, then simply put that number into the variable theHour. Otherwise, return theHour minus 12 (which converts hours 13 and higher to their 12-hour-clock counterparts).

11.
function showZeroFilled(inValue) {
  if (inValue > 9) {
     return ":" + inValue;
  }
  return ":0" + inValue;
}



This function is used to pretty up the output; when the minutes or seconds figure is 9 or under, it pads the figure with a leading zero.

12.
function showAmPm(thatTime) {
  if (thatTime < 12) {
     return (" AM ");
  }
  return (" PM ");
}



This function adds A.M. or P.M. to the time. If the passed variable thatTime is less than 12, then the value of the function is A.M.; otherwise it is P.M. Note that there is a leading space in the A.M. or P.M. text string so things look nice.

Tips

  • There's no simple and straightforward way to deal with Daylight Savings Time. Some browsers just don't handle it correctly. And unfortunately, you're also at the mercy of computer users knowing how to set up their computers to be aware when it's happening. Luckily, both Windows and Mac OS X have the ability to automatically set the time based on an Internet time server, which does take Daylight Savings into account, so it's less of a problem than it used to be. The bad news: JavaScript doesn't have a way to get at that information from the OS, so it can't tell if you're in a time and place for it to apply.

  • It's easy to add another city to the HTML without touching a single line of JavaScriptand it will all just work.

  • In this script, we use the toUTCString() method instead of the toGMTString() method; they work almost identically. In previous editions of this book, we used toGMTString() because toGMTString() was introduced in JavaScript 1.0, and toUTCString() came in with JavaScript 1.2; by using toGMTString(), we ensured that the script works even in very old browsers. Since those browsers are no longer in use, we changed to UT in this edition. The main difference between the two methods is that the toGMTString() method appends "GMT" to the end of the string, and the toUTCString() method appends "UTC" to the end of the string. Either way, you'll still have to strip off three characters in step 5.



Previous Page
Next Page