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 12.4 shows the HTML for the page; Script 12.5, with the JavaScript, shows you how to calculate dates in other time zones.

To display dates by time zone:

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



Inside the initDate() function, create the allTags variable. The command document.getElementsByTagName("*") is a handy trick—that 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.

Script 12.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"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Time Zones</title>
     <script 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 12.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 ";
							}
}

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 12.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 12.1 at the end of the chapter), saving the result in dateStr.

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 the universal 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 12.4.

Figure 12.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, which is passed the variable theHour. Then, if theHour is zero, return the result 12 (meaning the hour is 12 A.M.); otherwise continue with the function.

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 AM or PM to the time. If the passed variable thatTime is less than 12, then the returned value of the function is “AM”; otherwise it is “PM”. Note that there is a leading space in the AM or PM 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 JavaScript—and it will all just work.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.195.107