Moment.js set the base time from the server

前端 未结 3 736
难免孤独
难免孤独 2020-12-05 00:35

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

相关标签:
3条回答
  • 2020-12-05 01:12

    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);
    }
    
    0 讨论(0)
  • 2020-12-05 01:20

    title: Changing Time Source version: 2.11.0 signature: |

    moment.now = function () { return +new Date(); }

    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

    0 讨论(0)
  • 2020-12-05 01:29

    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();
      }
    }
    
    0 讨论(0)
提交回复
热议问题