View Full Version : Resolved World clock project

03-03-2012, 08:52 PM
Hello, I'm learning JavaScript and have a problem with a world clock.

I followed a tutorial and then added some buttons and variables to make the clock below (see code A), but it only works off the host computer's time and I need it to work off GMT.

I found some code (see code B) to get GMT but cannot find a way to tie it to my first chunk of code.

Any ideas?

Thanks in advance.

Code A:

<!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">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Jamie's World Clock</title>

<script language="javascript">

<!-- // Comment out with HTML if JavaScript unavailable

// Variable for a time zone
var timeZone = 0;

// Variable for location
var geoLoc = "London";

// Set location using child node
function setLocation() {
document.getElementById("location").firstChild.nodeValue = geoLoc;

function updateClock ( )


// Get current time from user's machine
var currentTime = new Date ( );

// Retrieve hours, minutes and seconds from new variable 'curretTime'
var localHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );


// Add a leading zero to mins and secs if less than 10

/* From tutorial: The ? and : symbols used above comprise the ternary operator.
This is a special operator that returns the value before the colon if the
condition before the query (?) is true, or the value after the colon if the
condition is false. It's a great way to write an if block in shorthand,
provided you only need to return a single value. */

// Put more simply: If x = less than 10 use 0 + currentMinutes else currentMinutes
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

// Variable for current hours
var currentHours = localHours + timeZone;

// Prevents negative time values eg 1.00am London = 8.00pm New York, not -4.00am
currentHours = (currentHours < 0 ? ((currentHours - 12) + 36) : currentHours);

// Ensures cannot go to 13.xx.xx PM+ and returns to AM
currentHours = ((timeZone + localHours) > 24 ? currentHours = (currentHours - 24) : currentHours);

// timeOfDay: If currentHours less than 12 = AM else PM
var timeOfDay = ( currentHours < 12 ) ? " AM" : " PM";

// 12 hour clock: If currentHours greater than 12 then -12 else currentHours
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

// 12 hour clock: If currentHours = 0 then 12 else currentHours
currentHours = ( currentHours == 0 ) ? 12 : currentHours;

// Put it all together in one variable
var currentTimeString = currentHours +":" + currentMinutes + ":" + currentSeconds + timeOfDay;


// Create the following span container: <span id="clock">&nbsp;</span>...
// see HTML below script

/* From tutorial: By placing the &nbsp; inside the span element, we're creating
a child text node for the span in the DOM. We can then populate the container
with our time string by retrieving this child text node then setting its
nodeValue property, as follows:

document.getElementById("clock").firstChild.nodeValue = currentTimeString;

} // End function updateClock

// New York function
function changeZone() {
updateClock(); // Run updateClock function to get immediate change rather than waiting for <body> setInterval
document.getElementById("location").firstChild.nodeValue = geoLoc; // Change geoLoc variable using child node
alert ("Your time zone has been set to " + geoLoc + "."); // Alert the user to the change of time zone

// --> end HTML comment



<!-- Runs updateClock function on body load and repeats every second -->
<body onLoad="setLocation(); updateClock(); setInterval('updateClock()', 1000 )">

<!-- Runs updateClock function on body load and repeats every second -->
<span id="clock">&nbsp;</span><br />

<p>Your current time zone is <span id="location">&nbsp;</span>.</p>

<button onclick="timeZone = -5; geoLoc = 'New York'; changeZone()">New York</button><br />
<button onclick="timeZone = 0; geoLoc = 'London'; changeZone()">London</button><br />
<button onclick="timeZone = 4; geoLoc = 'Dubai'; changeZone()">Dubai</button><br />
<button onclick="timeZone = 8; geoLoc = 'Beijing'; changeZone()">Beijing</button><br />
<button onclick="timeZone = 11; geoLoc = 'Sydney'; changeZone()">Sydney</button><br />



Code B:

function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;

getTime('GMT', function(time){
// This is where you do whatever you want with the time:

Philip M
03-03-2012, 09:04 PM

Have a look at getUTChours(), getUTCdate() and so on.

Have you tried the search feature of this form - "World Clock" returns several useful threads.

<script language=javascript> is long deprecated and obsolete. Use <script type = "text/javascript">.
The <!-- and //--> comment (hiding) tags have not been necessary since IE3 (i.e. since September 1997). If you see these in some published script it is a warning that you are looking at ancient and perhaps unreliable code.

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

03-03-2012, 09:41 PM
I've had a look at getUTChours() but that also seems to get the machine's local time.

I've also searched extensively for world clock tutorials but don't understand a lot of what I see because I'm new.

03-03-2012, 10:19 PM
JavaScript always works off the local computer time. When you specify any of the UTC methods it uses the computer's timezone offset to work out what the UTC time (previously known as GMT) is based on the assumption that the computer has both the time set correctly for their local time and the timezone offset correct for their timezone. If either is incorrect then JavaScript has no way to work out what time it is.

If you assume that the time and timezone are correct (and for a JavaScript only solution there is no alternative) then by making use of both you can display the time in any timezone - for example the clocks on http://javascript.about.com/library/blclockm1.htm display two fixed timezones and also the local time.

03-04-2012, 08:48 AM
Great, thanks. I understand now.

Philip M
03-04-2012, 10:48 AM
Be aware that another problem with time zones is Daylight Saving Time (DST). Not all countries use DST, and those that do use it apply it between different dates. Although it is possible to detect whether a country does use DST, it is not possible to tell whether DST is actually in operation on a particular date.

03-04-2012, 07:04 PM
Although it is possible to detect whether a country does use DST, it is not possible to tell whether DST is actually in operation on a particular date.

Yes it is possible to detect:

Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();

With those two methods added to the date the dst() method will be true if the computer it is run on is set for daylight saving time and false if it isn't. The timezone offset is actually changed based on the daylight saving time settings for the location that the computer is set to so by comparing the 1st Jan and 1st July offsets you can determine whether the place uses daylight saving time and which of those two dates is on daylight saving and then simply compare the current date offset to the one not on daylight saving to determine if that date is or isn't on daylight saving based on the start and end dates the operating system uses to set the offset.

Philip M
03-04-2012, 08:52 PM
That detects whether the place uses DST. I do not see how it can identify whether or not DST is actually in operation on some specific date. Let us say for example 20th May.

03-04-2012, 09:40 PM
That detects whether the place uses DST. I do not see how it can identify whether or not DST is actually in operation on some specific date. Let us say for example 20th May.

The first of the two methods determines if the place uses DST by checking if the timezone offset is the same on 1st January and 1st July.

If the offset is different for those two dates then Whichever of those is the most negative is the one where DST applies (since JavaScript stores the offsets as the amount of time to adjust the current time by to get GMT).

If you test the timezone offset for any other date of the year then it will give you one of the two values depending on whether the operating system considers DST to apply to that date or not. By comparing the offset that JavaScript has stored for 20th May to the larger of the offsets that JavaScript applies on 1st January and 1st July you can determine whether whether DST applies on that date.

It relies entirely on the computer being set to the correct country and location and the start and end of DST being correctly identified for that location (when Eastern Australia last changed when DST starts and finishes not everyone had updated their operating system with the DST patch and so thase that hadn't were reporting incorrectly for dates between the old and new start dates).

Just to make it clearer. Here in Sydney with the way my computer is set the 1st Jan offset is -11 hours and the 1st July offset is -10 hours and so this location has DST and 1st Jan is within the DST period (since it has the smaller number). The 1st May offset is -10 hours and so that date is not on DST. So simply comparing the offsets that JavaScript returns for those three dates you can not only tell whether the computer is set to use DST but can also tell whether DST applies on any given date.