javascript Moment.js 从服务器设置基准时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19629561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:15:10  来源:igfitidea点击:

Moment.js set the base time from the server

javascriptdatemomentjs

提问by TYRONEMICHAEL

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

例如这样的事情

moment().set('server time')

Then moment()would return the Date Object based on server's time as opposed to the time from the client's computer.

然后moment()将根据服务器的时间而不是客户端计算机的时间返回日期对象。

Does this functionality exist, and if not what are some recommended methods you would use? Right now I am polling the server to get the server's time, but as you can imagine this is not very efficient.

此功能是否存在,如果不存在,您会使用哪些推荐方法?现在我正在轮询服务器以获取服务器的时间,但是您可以想象这不是很有效。

UPDATED WITH CODE EXAMPLE AND SUMMARY

更新了代码示例和摘要

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().

我正在构建一个拍卖应用程序。所以服务器时间很关键。例如,如果用户篡改了他们的时间设置或他们的时间被手动配置,客户可能会看到已经结束的拍卖,而实际上它还有几分钟的时间。所有时间检查显然都是在服务器上完成的,但这就是我需要客户端和服务器同步的原因。现在您可以看到我每隔几秒钟轮询服务器以获取最新时间。但是,我需要设置 moment() 以从我从服务器传递的变量中调用基准时间。所以每次我调用 moment() 时,它都是基于最初传入的时间而不是 new Date() 的时间。

app.getTime = ->
    setInterval ->
        $.get app.apiUrl + 'public/time', (time)  -> 
            app.now = moment(time).format('YYYY-MM-DDTHH:mm')
    , app.fetchTimeInterval

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}'"

Instead I would like to call the following and it returns the time from server which I only need to configure once with a get request from the url above.

相反,我想调用以下内容,它从服务器返回时间,我只需要使用来自上面 url 的 get 请求配置一次。

 now = moment().format('YYYY-MM-DDTHH:mm')

回答by Jacques Snyman

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

回答by duckbrain

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

从 Moment.js 2.10.7 开始,可以更改时间源(请参阅介绍它的PR)。

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

您可以使用它来同步 Moment.js 看到的时间与您服务器的时间。

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

回答by Ali Jamal



title: Changing Time Source version: 2.11.0 signature: |

标题:更改时间源版本:2.11.0 签名:|

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

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).

如果要更改 Moment 看到的时间,可以指定一个方法,该方法返回自 Unix 纪元(1970 年 1 月 1 日)以来的毫秒数。

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.

这将在调用时使用moment(),并且在从 中省略令牌时使用的当前日期 format()。通常,任何需要当前时间的方法都会在幕后使用它。

Changing Time Source

更改时间源