I want to include a JavaScript world time clock like http://www.dynamicdrive.com/dynamicindex6/localtime.htm to my homepage but I don't want to change it every time when the DST changes for a time zone. Is it possible to sync it automatically with an official time server so that I can display the current time for different places live and without any changes after DST?
Use the standard date
function along with date_default_timezone_set
.
$timezones = array("Australia/Brisbane", "America/New York", "Europe/London");
foreach ($timezones as $tz) {
date_default_timezone_set($tz);
echo "The time in $tz is: " . date('r');
}
It handles all the daylight savings and everything for you.
You can find the list of supported timezones here: http://www.php.net/manual/en/timezones.php
Edit: Javascript implementation:
Use the above method to get PHP to output all the different timezones you're interested in, but use
date('Z')
to get the seconds offset from UTC. Output it using JSON or something so Javascript can use it:var offsets = { 'Brisbane' : 36000, 'Sydney' : 42000, 'London' : 0 };
Loop through them all, adding and subtracting the offsets as necessary.
for (var city in offsets) { var d = new Date(); d.setTime(d.getTime() + offsets[city] * 1000); alert('The time in ' + city + ' is ' + d.toUTCString()); }
Put the above into a function which is called every second, using setInterval
A caveat though: it won't be guaranteed accurate, since in theory, a location's timezone could change while someone has the window open (they could be on the border of DST). It's not very likely, and a page refresh would show the right times, so it's probably not a big deal.