Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    New Coder
    Join Date
    Nov 2011
    Posts
    32
    Thanks
    15
    Thanked 0 Times in 0 Posts

    World clock project

    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:
    Code:
    <!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>
    <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 THE TIME
    	
    		// 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 ( );
    	
    	// FORMAT THE TIME
    		
    		// 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;
    		
    	// DISPLAYING THE CLOCK
    	
    		// 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
    		
    </script>
    
    </head>
    
    <!-- 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 />
    
    </body>
    
    </html>
    Code B:
    Code:
    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));
        };
        document.getElementsByTagName('head')[0].appendChild((function(){
            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:
        alert(time);
    });
    Last edited by Jimbolgs; 03-04-2012 at 07:51 AM.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,920
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    http://www.w3schools.com/jsref/jsref_obj_date.asp

    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.
    Last edited by Philip M; 03-03-2012 at 08:10 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    New Coder
    Join Date
    Nov 2011
    Posts
    32
    Thanks
    15
    Thanked 0 Times in 0 Posts
    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.

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,630
    Thanks
    0
    Thanked 648 Times in 638 Posts
    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.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    Jimbolgs (03-04-2012)

  • #5
    New Coder
    Join Date
    Nov 2011
    Posts
    32
    Thanks
    15
    Thanked 0 Times in 0 Posts
    Great, thanks. I understand now.

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,920
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,630
    Thanks
    0
    Thanked 648 Times in 638 Posts
    Quote Originally Posted by Philip M View Post
    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:

    Code:
    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.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,920
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,630
    Thanks
    0
    Thanked 648 Times in 638 Posts
    Quote Originally Posted by Philip M View Post
    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.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •