两个时区格式日期之间的 moment.js 差异

Gra*_*ant 3 javascript momentjs

我必须计算设定时间和当前服务器时间之间的时间差。

我正在使用 momentjs 和 moment 时区库。

这是我所拥有的:

var serverTime = moment.tz(new Date(), "Europe/Berlin").format();
var bar = moment.tz("2016-05-14 00:00:00", "Europe/Berlin").format();
var baz = bar.diff(serverTime);

console.log('server time is: ' + serverTime);
console.log('time diff is: ' + baz);
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误:

TypeError: bar.diff is not a function
Run Code Online (Sandbox Code Playgroud)

是否可以在两个时区格式的日期之间进行区分?如果没有,使用 momentjs 库进行此类计算的最佳方法是什么?

Mat*_*int 6

format 产生一个字符串,所以在你需要一个字符串之前不要使用它。

var now = moment.tz("Europe/Berlin");
var bar = moment.tz("2016-05-14 00:00:00", "Europe/Berlin");
var baz = bar.diff(now);

console.log('current time is: ' + now.format());
console.log('time diff is: ' + baz);
Run Code Online (Sandbox Code Playgroud)

请注意,除非您在服务器上运行此代码,否则这不是“服务器时间”。只要它在客户端上运行,它仍然基于客户端的时钟——即使您使用不同的时区。