TYRONEMICHAEL TYRONEMICHAEL - 5 months ago 64
Javascript Question

Moment.js set the base time from the server

I have been reading the documentation, and cannot seem to find a method to set the date from the server as opposed to the client?

For example something like this

moment().set('server time')


Then moment() would return the Date Object based on server's time as opposed to the time from the client's computer.

Does this functionality exist, and if not what are some recommended methods you would use? Right now I am polling the server to get the server's time, but as you can imagine this is not very efficient.

UPDATED WITH CODE EXAMPLE AND SUMMARY



I am building an auction application. So server time is critical. For example if the user has tampered with their time settings or their time has been manually configured, the client might see an auction that has already ended, when in fact it still has a few minutes left. All time checks are obviously done on the server, but that is why I need the client and server to be in sync. Now you can see I am polling the server to get the latest time every few seconds. However what I need is to set moment() to call the base time from the variable I pass from the server. So everytime I call moment() it bases the time from the time passed in initially instead of new Date().

app.getTime = ->
setInterval ->
$.get app.apiUrl + 'public/time', (time) ->
app.now = moment(time).format('YYYY-MM-DDTHH:mm')
, app.fetchTimeInterval


Somewhere else in my application I use the app's server time like so

collection = new Auction.DealershipBasket [], query: "?$orderby=Ends&$filter=Ends lt datetime'#{app.now}'"


Instead I would like to call the following and it returns the time from server which I only need to configure once with a get request from the url above.

now = moment().format('YYYY-MM-DDTHH:mm')

Answer

The best way to do this would be to ask the server once for the current time and then compute the offset between the server time and the client time. A function can then return the server time at any stage by using the current client date and applying the server difference.

Here's an example:

var serverDate;
var serverOffset;
$.get('server/date/url', function(data){
   // server returns a json object with a date property.
   serverDate = data.date;
   serverOffset = moment(serverDate).diff(new Date());
});

function currentServerDate()
{
    return moment().add('milliseconds', serverOffset);
}