building a timestamp in javascript

I get the following pieces of data injected in the page when the page loads:

var TimeZoneOffset = parseFloat($('#DataUserTimeZoneOffset').html());
var TheDay = parseInt($('#DataUserDayToday').html(), 10);
var TheMonth = parseInt($('#DataUserMonthToday').html(), 10);
var TheYear = parseInt($('#DataUserYearToday').html(), 10);
var TheHours = parseInt($('#DataUserTimeStampHours').html(), 10);
var TheMinutes = parseInt($('#DataUserTimeStampMinutes').html(), 10);

I build the date like this on document.ready:

  • Handle task time in asp.net
  • Disable a checkbox in javascript and recognize it as checked on the server side
  • How to use javascript in .ascx pages
  • Call a javascript function on RadioButton click
  • Values lost on postback when changed by javascript
  • Passing selected value of dropdownlist in URL
  • var TheDateToday = new Date();
    TheDateToday.setUTCFullYear(TheYear, TheMonth, TheDay);
    TheDateToday.setUTCHours(TheHours, TheMinutes, 0, 0);
    

    and then, I determine the local time like this:

    var TheLocalTime = new Date(TheDateToday.getTime() + TimeZoneOffset);
    

    I don’t want to rely on the user’s clock at all in terms of giving me the time. I use the user’s time to calculate an offset between the local time I created and the time on the user’s machine. So I do something like this:

    var UserBrowserTime = new Date();
    var UserTimeOffset = TheLocalTime.getTime() - UserBrowserTime.getTime();
    

    On my application, the user creates objects that are stored in his local storage. These objects have a property called TimeCreated. Every minute, these objects are ajaxed back to the server. However, if the user disconnects from the site, there may still be some local storage waiting to be ajaxed when he comes back so I can’t use the time at which I receive the ajax call on the server as the time at which these objects where created. Instead, I’m looking to ajax back the server the object and its TimeCreated timestamp. To build this timestamp, I want to get the user’s time and add to it the UserTimeOffset that I’m creating when the page loads.

    Is this going to work? Am I over-complicating things? The problem to solve is that data stored in local storage can be ajaxed much later than the time at which it was created and when the server receives the data, it must know at what time the object was created.

    An alternative I’m considering is build my own clock with the SetTimeout function and every 1000ms, add a second to the UserBrowserTime variable and use that as my timestamp.

    Thanks for your suggestions.

  • Get contents of local folder in javascript (or ASP.NET VB)
  • How to handle inline code with RequireJS Optimization
  • Using Alert in Response.Write Function in ASP.NET
  • assign C# string of array or string[] to javascript array
  • Need a Javascript calendar that should only show next dates corresponding to the date in textbox
  • JQuery UI - Add dblclick Event to Modal dialogs
  • 2 Solutions collect form web for “building a timestamp in javascript”

    The usual trick is to do everything in UTC. Create a local date object and set it using the UTC data from the server (which I guess is what you are doing now).

    You can then determine the local offset (i.e. difference between the local system and “correct” time sent from the server) as:

    var offset = TheDateToday - new Date();
    

    Now whenever you need a time you do:

    var now = new Date((new Date()).getTime() + offset);
    

    You will miss any latency between the local machine and server, hopefully that is short. When you send things back to your server, use a UTC timestamp. A simple function is:

    function padZ(n) {
      return (n<10? '0' : '') + n;
    }
    
    function getUTCTimestamp(d) {
      return d.getUTCFullYear() + '-' + padZ(d.getUTCMonth() + 1) +
             '-' + padZ(d.getUTCDate()) + 'T' + padZ(d.getUTCHours()) + ':' +
             padZ(d.getUTCMinutes()) + ':' + padZ(d.getUTCMinutes()) + 'Z';
    }
    
    var d = new Date();
    alert(d + '\n' + getUTCTimestamp(d));  // something like 2011-11-10T14:18:23Z
    

    I wonder if either of these can be effective with latency. I don’t know the answer in practice, but the time coming from the server certainly isn’t guaranteed to get processed immediately.

    If the page is slow to render, you could end up with seconds ticking away between the time your server provides the reference time and when it is compared to the client time.

    Of course, based on your examples, I’m guessing that off by a minute wouldn’t kill things? You could, of course, easily be off by a minute, even if there are only a few seconds latency between receipt and comparison unless you’re tracking to the second.

    Since JS isn’t a truly threaded language, anything CPU intensive could distort setTimeout‘s accuracy and cause that approach to slowly lose accuracy as well.

    An approach I utilized in the past to good results was to implement an ntpd-like script that polls the server, syncs with local time, and then occasionally polls for updates and sees if we’ve lost our sync. This is not a difficult bit to implement as long as you don’t mind a few seconds variance (due to network latency).

    Of course, utilizing a solution like nodejs or another server guaranteed to produce snappy and zippy results, delivered over a CDN like AWS can really shave the discrepancies to near perfection, assuming this sort of accuracy is even necessary.