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
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);
}
title: Changing Time Source version: 2.11.0 signature: |
If you want to change the time that Moment sees, you can specify a method that returns the number of milliseconds since the Unix epoch (January 1, 1970).
The default is:
moment.now = function () {
return +new Date();
}
This will be used when calling moment()
, and the current date used when tokens are omitted from
format()
. In general, any method that needs the current time uses this under the hood.
Changing Time Source
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();
}
}