Calculating server time with a Javascript date object

A few weeks ago at work I was assigned to develop a warning banner to be displayed across our intranet data entry site to warn users of impending code launches. Our users tend to leave pages open for a while as they enter data, so we wanted the banner to display dynamically. For example, if someone had a page open during a specified warning time, the banner should be displayed without having to refresh the page. My solution was a 60-second time-comparison poll closed over by an anonymous function.

My initial implementation created a Javascript date object and compared the results of its getUTCDay, getUTCHours, and getUTCMinutes() functions to the developer-specified warning times. If the current time was greater than the set warning time, the banner was displayed. There’s some cookie-handling in there so that the user can close the warning banner and not have it show up until the next warning time, but no bother.

A potential problem arose in that Javascript uses the client’s local time to create date objects. Thus if the user’s computer had incorrect time, the warning banner wouldn’t display when it was supposed to. A better way to go about it would be to use the server’s time instead of the client’s.

Luckily I could make use of Mason’s preprocessor to insert the results of the Perl time() function into clientside Javascript to get the server time. I first calculate the client/server time difference and then use it to create an accurate date object inside the poll function.

// Determine delta between client and server times
var time_delta = (<% time %> * 1000) - Date.now();

function launchWarningPoll() {
    var d = new Date(Date.now() + time_delta);
    ...
}

As launchWarningPoll() gets called every 60 seconds, it will accurately portray the server time regardless of how much the user’s local time is off.

blog comments powered by Disqus