TYR*_*AEL 22 javascript date momentjs
我一直在阅读文档,似乎找不到从服务器而不是客户端设置日期的方法?
例如像这样的东西
moment().set('server time')
Run Code Online (Sandbox Code Playgroud)
然后,moment()将根据服务器的时间返回Date对象,而不是来自客户端计算机的时间.
是否存在此功能,如果不存在,您将使用哪些推荐方法?现在我正在轮询服务器以获取服务器的时间,但是你可以想象这不是很有效.
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
Run Code Online (Sandbox Code Playgroud)
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}'"
Run Code Online (Sandbox Code Playgroud)
相反,我想调用以下内容,它从服务器返回时间,我只需要使用上面的url的get请求配置一次.
now = moment().format('YYYY-MM-DDTHH:mm')
Run Code Online (Sandbox Code Playgroud)
Jac*_*man 26
执行此操作的最佳方法是向服务器询问当前时间,然后计算服务器时间与客户端时间之间的偏移量.然后,函数可以通过使用当前客户端日期和应用服务器差异在任何阶段返回服务器时间.
这是一个例子:
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);
}
Run Code Online (Sandbox Code Playgroud)
duc*_*ain 22
从Moment.js 2.10.7开始,可以改变时间源(参见引入它的PR).
您可以使用它来将Moment.js看到的时间与服务器的时间同步.
function setMomentOffset(serverTime) {
var offset = new Date(serverTime).getTime() - Date.now();
moment.now = function() {
return offset + Date.now();
}
}
Run Code Online (Sandbox Code Playgroud)