以小时为单位获得时区差异

时间:2015-11-13 01:58:10

标签: javascript node.js timezone momentjs timezone-offset

我想通过Node.js时刻模块获得纽约和香港之间的时区差异。我做了一些初步工作。

var NewYork_time_hr = moment().tz("America/New_York").format('HH'); 
var HongKong_time_hr = moment().tz("Asia/Hong_Kong").format('HH');

然后我可以继续编写一个函数来计算2个时区之间的差异,以小时为单位。我希望有一种更简单的方法。

使用矩形库有更优雅,更简单的方法吗?

1 个答案:

答案 0 :(得分:17)

不确定“更简单”,但更正确(因为并非所有时区彼此相隔一小时):

// get the current time so we know which offset to take (DST is such bullkitten)
var now = moment.utc();
// get the zone offsets for this time, in minutes
var NewYork_tz_offset = moment.tz.zone("America/New_York").offset(now); 
var HongKong_tz_offset = moment.tz.zone("Asia/Hong_Kong").offset(now);
// calculate the difference in hours
console.log((NewYork_tz_offset - HongKong_tz_offset) / 60);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.4.1/moment-timezone-with-data-2010-2020.min.js"></script>