Categories:

Displaying the Live Local Time of Any City with Google Time Zone API

Now that we know how to reliably get the date and time of any location thanks to Google Time Zone API, we can do with it anything the standard JavaScript Date object grants us. A popular extension is to show that time in, well, real time:

Example:

Tokyo Time:
LA Time:
Toronto Time:
Paris Time:

Here is function currentlocaltime() behind the magic. It takes any Latitude and Longitude tuple and displays the corresponding live time inside a DIV:

<div class="timebox">Tokyo Time: <span id="tokyotime"></span></div>
<div class="timebox">LA Time: <span id="latime"></span></div>
<div class="timebox">Toronto Time: <span id="torontotime"></span></div>
<div class="timebox">Paris Time: <span id="paristime"></span></div>

<script>
var apikey = 'YOUR_API_KEY_HERE'
var daysofweek = ['Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']

function currentlocaltime(divid, loc){
	var container = document.getElementById(divid)
	var targetDate = new Date() // Current date/time of user computer
	var timestamp = targetDate.getTime()/1000 + targetDate.getTimezoneOffset() * 60 // Current UTC date/time expressed as seconds since midnight, January 1, 1970 UTC
	var apicall = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + loc + '×tamp=' + timestamp + '&key=' + apikey

	var xhr = new XMLHttpRequest() // create new XMLHttpRequest2 object
	xhr.open('GET', apicall) // open GET request
	xhr.onload = function(){
		if (xhr.status === 200){ // if Ajax request successful
			var output = JSON.parse(xhr.responseText) // convert returned JSON string to JSON object
			console.log(output.status) // log API return status for debugging purposes
			if (output.status == 'OK'){ // if API reports everything was returned successfully
				var offsets = output.dstOffset * 1000 + output.rawOffset * 1000 // get DST and time zone offsets in milliseconds
				var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of target location
				var refreshDate = new Date() // get current date again to calculate time elapsed between targetDate and now
				var millisecondselapsed = refreshDate - targetDate // get amount of time elapsed between targetDate and now
				localdate.setMilliseconds(localdate.getMilliseconds()+ millisecondselapsed) // update localdate to account for any time elapsed
				setInterval(function(){
					localdate.setSeconds(localdate.getSeconds()+1)
					container.innerHTML = localdate.toLocaleTimeString() + ' (' + daysofweek[ localdate.getDay() ] + ')'
				}, 1000)
			}
		}
		else{
			alert('Request failed.  Returned status of ' + xhr.status)
		}
	}
	xhr.send() // send request
}

currentlocaltime('tokyotime', '35.731252, 139.730291')
currentlocaltime('latime', '34.052046, -118.259335')
currentlocaltime('torontotime', '43.656090, -79.387679')
currentlocaltime('paristime', '48.856805, 2.348242')
</script>

The highlighted lines pick out what's new from the code we've already seen on the previous page to bring the time to life. Once the current localdate has been retrieved, we make sure it's as current as possible, by creating another instance of the Date() object to calculate the number of milliseconds it took to connect with Google Time Zone API, and append that extra time (in milliseconds) to the localdate object.

With an up to date localdate object in hand, all that's left is to increment it by 1 second every second, and display the result to the rest of the world!

Creating a live local clock

For the final part of this tutorial, lets push the evelope even more, and feed our live time to a CSS3 rendered clock to breathe life into it:

Tokyo Time
Vancouver, BC Time

You can view the full source code on the standalone clock page here.

End of Tutorial