Moment.js set the base time from the server

Since Moment.js 2.10.7 it is possible to change the time source (see the PR that has introduced it).

You can use it to synchronize the time Moment.js sees with your server's time.

function setMomentOffset(serverTime) {
  var offset = new Date(serverTime).getTime() - Date.now();
  moment.now = function() {
    return offset + Date.now();
  }
}

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);
}