James.Cridland.net

Have an accurate clock

Thing is, your clock on your computer might be wrong, but those nice JavaScript clock scripts don't take that into account. I'd like to be able to tell you what the correct time is here in the UK (in fact, the time of this server), but I'd like your machine to keep that updated so it changes before your very eyes. So, this bit of PHP and JavaScript-combined does just that. If my server is the correct time (it should be), then so will this clock be, too.

There's quite a cool version of this script on Peter van der Gulden's site; and an even smarter thing with an ASCII globe here which also uses this script.

It does this: 5.21am - Sunday 6 July 2008

...and the code looks like this. Keep it all together; no need to muck about with HEAD statements here.

<script LANGUAGE="JavaScript">
<!--
//Work out correct time to update
//Grab time from this server
var cridlandnow = new Date("<? echo date("M d Y G:i:s"); ?>");
var cridlandcorrection = (new Date() - cridlandnow);
//Only update every 30 secs
timeID=window.setTimeout("cridlandtimeupdate();", 1000);

function cridlandtimeupdate() {
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
//Get current date
cridlandnow1 = new Date();
//Apply the correction
var expdate = cridlandnow1.getTime();
expdate -= cridlandcorrection;
cridlandnow1.setTime(expdate);
cridlandhours = cridlandnow1.getHours();
if (cridlandhours>=13) {cridlandhours-=12;}
if (cridlandnow1.getHours()>=12) {cridlandAorP="pm";}
else
{cridlandAorP="am"; }
cridlandminutes = cridlandnow1.getMinutes();
if (cridlandminutes < 10) {cridlandminutes = "0" + cridlandminutes};
cridlandc=cridlandhours+"."+cridlandminutes+cridlandAorP+" - "+weekday[cridlandnow1.getDay()]+" "+cridlandnow1.getDate()+" "+monthname[cridlandnow1.getMonth()]+" "+cridlandnow1.getFullYear();

if (document.all) {
//This is IE or Opera
document.all['cridlandtime'].innerHTML = cridlandc;
} else {
//This is Mozilla
document.getElementById("cridlandtime").innerHTML = cridlandc;
}
timeID=window.setTimeout("cridlandtimeupdate();",1000);
}
// --></script>
<p><span id='cridlandtime'><? echo date("g.ia")." - ".date("l j F Y");?></span></p>

Download this code

Compatibility
I don't bother with compatibility with Netscape 4; this only works with Mozilla/Gecko things like Netscape 6, and MSIE. However, it doesn't matter if JavaScript has been turned off... it just won't update, that's all. It's like magic, except without the pixies.

Also see...
Stuart Homfray's enhancement to this script, which you might find handy if you're hosted in the USA but wish to give a proper UK time. Or the other way round.