Moment.js set the base time from the server

前端 未结 3 752
难免孤独
难免孤独 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);
    }
    

提交回复
热议问题