NTP for Javascript

posted October 24th 2005 at 0412 EDT in All, Javascript, ajax

So you want to display the current time in the browser, but you know computers are suprisingly 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 but only for the sync() operation.


<script language="javascript" src="/js/prototype.js"></script>
<script language="javascript" src="/js/NTP.js"></script>
<script language="javascript">
NTP.sync();
</script>
 

NTP.sync() will make a configurable number of requests to the server (see below for serverside scripts in PHP, Python and ColdFusion). It passes the client timestamp in miliseconds UTC time.

GET /sandbox/gettime.php?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()


var time = new Date();
time = Date(NTP.fixTime(time.getTime()));
 

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.


// 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 = Array(12);
    monthNames[0] = "JAN";
    monthNames[1] = "FEB";
    monthNames[2] = "MAR";
    monthNames[3] = "APR";
    monthNames[4] = "MAY";
    monthNames[5] = "JUN";
    monthNames[6] = "JUL";
    monthNames[7] = "AUG";
    monthNames[8] = "SEP";
    monthNames[9] = "OCT";
    monthNames[10] = "NOV";
    monthNames[11] = "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);
}
 

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.

8 Responses

  1. #1 Yeago
    2 years ago

    gettime.asp

    <%@LANGUAGE=”VBSCRIPT”%>
    <!–#include file=”Conn.asp” –>
    <%
    Set Conn = Server.CreateObject(”ADODB.Connection”)
    Conn.Open(CleanConn)

    set result = Conn.Execute(”SELECT DATEDIFF(SS,’1/1/1970′,’” & NOW() & “‘) AS result”)

    mm = result(”result”) * 1000

    if Request.QueryString(”t”) = “” then
    response.write “0:” & mm
    else
    Response.Write Request.QueryString(”t”) & “:” & mm
    end if

    %>

  2. #2 jehiah
    2 years ago

    @Yeago, thanks for the asp version =)

  3. #3 Yeago
    2 years ago

    Sure buddy! =) Thank you for the only JavaScript Clock not made in the 1990s. Haha.

    NOTE to users of the asp version: That last IF statement is fudged since a bad/null GET variable “t” isn’t passed as “”. Woops. =)

  4. #4 Yeago
    1 year, 8 months ago

    Anyone have trouble with this clock being a half hour off in some cases?

  5. #5 jehiah
    1 year, 8 months ago

    @yeago, i havn’t had a problem with it being 30 minutes off but i did realize that since i am using a zulu clock i can display it with the utc methods for example: getUTCHours() instead of getHours(); and skip offsetting the time by the timezone. I surmize that you might have some odd timezone settings.

  6. […] I told my gracious web host about this project after I was approximately 90% complete with it, and his response was: “Did you use NTP?”, with which I replied: “What is NTP?” Ugh. There is even a JavaScript implementation. […]

  7. #7 Bassam
    8 months, 4 weeks ago

    Thanks for the help. I have a question though:
    My GMT time was 4 hours off, but then I noticed that you are adding 4 hours to your timestamp in gettime.php. I removed the 4 hours addition part. Now I’m getting the right time. I am wondering though why you added this extra 4 hours in the first place?

  8. #8 archis
    7 months, 3 weeks ago

    :D

Leave a comment