NTP for Javascript

by @jehiah on 2005-10-24 04:12UTC
Filed under: All , Javascript , ajax

So you want to display the current time in the browser, but you know computers are surprisingly horrible at keeping time. Worse yet you can’t dictate NTP as a requirement to people browsing your site. NTP for Javascript to the rescue.

Go ahead. try it out. Change your PC’s time and click the rerun link in the next line.

The corrected current time is

NTP for Javascript uses [prototype.js](http://prototype.conio.net/) but only for the `sync()` operation. [html] [/html] `NTP.sync()` will make a configurable number of requests to the server. It passes the client timestamp in milliseconds UTC time. > GET /sandbox/gettime?t=1130036017399 Creates the following response with the offset and a copy of the timestamp which the offset is based. The following response shows an 11.1 second offset. > 11195:1130036017399 An average of the offset responses from the server get stored in the cookie `NTPClockOffset` after taking into account network delay. To make use of this offset value pass a timestamp to `NTP.fixTime()` [js] var time = new Date(); time = Date(NTP.fixTime(time.getTime())); [/js] Without a parameter, `NTP.fixTime()` will return an adjusted UTC timestamp. Now We can Create a simple Clock to display the Correct time (or add one line to modify Ray Stotts code) to give us the corrected clock you see at the top of this page. [js] // Zulu-time clock function jsClockGMT(){ // Copyright 1999 - 2001 by Ray Stott if (!document.getElementById('clock0')) { return; } gmtMS = NTP.fixTime(); // offset for how bad our clock is off zulu to zulu var gmtTime = new Date(gmtMS); // build a new object so we get the right txt back var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"]; var hour = gmtTime.getUTCHours(); var minute = gmtTime.getUTCMinutes(); var second = gmtTime.getUTCSeconds(); var year = gmtTime.getUTCFullYear(); var month = monthNames[gmtTime.getUTCMonth()]; var day = gmtTime.getUTCDate(); var temp = day + " " + month + " " + year; temp += " " + ((hour < 10) ? "0" : "") + hour; temp += ((minute < 10) ? ":0" : ":") + minute; temp += ((second < 10) ? ":0" : ":") + second; temp += " Z "; document.getElementById('clock0').innerHTML = temp; setTimeout("jsClockGMT()",1000); } [/js]

Download

Of course this assumes you are running ntpd on your server against pool.ntp.org or have some other way to keep your server synced.

Subscribe via RSS ı Email
© 2023 - Jehiah Czebotar