PHP/JS TimeZone'd Based Clocks

Soldato
Joined
3 Jun 2005
Posts
3,117
Location
The South
Hi all,

I'm wanting to place a few clocks on a page - one displaying the time in London, the other displaying the time in Sydney. These have got to work independently of the user/viewers own timezone/location and adjust themselves according to DST.

Now, i've thrown together the code below -
Code:
<?php
$UTC_Timezone = new DateTimeZone("UTC");
$London_Timezone = new DateTimeZone("Europe/London");
$Sydney_Timezone = new DateTimeZone("Australia/Sydney");
$UTC_Time = new DateTime("now", $UTC_Timezone);
$London_Offset = $London_Timezone->getOffset($UTC_Time);
$Sydney_Offset = $Sydney_Timezone->getOffset($UTC_Time);
?>
<html>

<body>
	London - <span id="LondonTime"></span>
	<br>
	Sydney - <span id="SydneyTime"></span>
</body>
<script type="text/javascript">	
	function clocks() {
		// Local Time
		var UTC_Time = Date.now();
	
		// UK
		var London_Time = new Date(UTC_Time + <?php echo ($London_Offset*1000); ?>);
		var nhours=London_Time.getUTCHours();
		var nmins=London_Time.getUTCMinutes();
		var nsecs=London_Time.getUTCSeconds();
		if (nhours < 10) nhours = "0"+nhours;
		if (nmins < 10) nmins = "0"+nmins;
		if (nsecs < 10) nsecs = "0"+nsecs;
		document.getElementById('LondonTime').innerHTML = (nhours+":"+nmins+":"+nsecs);
	
		// AUS Sydney
		var Sydney_Time = new Date(UTC_Time + <?php echo ($Sydney_Offset*1000); ?>)
		var nhours=Sydney_Time.getUTCHours();
		var nmins=Sydney_Time.getUTCMinutes();
		var nsecs=Sydney_Time.getUTCSeconds();
		if (nhours < 10) nhours = "0"+nhours;
		if (nmins < 10) nmins = "0"+nmins;
		if (nsecs < 10) nsecs = "0"+nsecs;
		document.getElementById('SydneyTime').innerHTML = (nhours+":"+nmins+":"+nsecs);
	
		setTimeout('clocks()',1000);
	}
	clocks();
</script>
</html>
http://phpfiddle.org/lite/code/qcax-53u1

However, it does seem a little 'bodgy', perhaps a bit long-winded and while it does appear to work, i'm not overly convinced getOffset() adjusts according to the timezone DST (can't see anything in the PHP manual).

So the questions are, are there likely to be issues with what i've done? And/or, is there a better/more efficient method (possibly moment.js?)?

Cheers for any advice/help :)
 
Back
Top Bottom