javascript 获取以小时为单位的时差与时刻
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33684748/
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
Get timezone difference in hours with moment
提问by user781486
I would like to get the timezone difference between New York and Hong Kong with Node.js moment module. I have done some preliminary work.
我想使用 Node.js 时刻模块获取纽约和香港之间的时差。我做了一些前期工作。
var NewYork_time_hr = moment().tz("America/New_York").format('HH');
var HongKong_time_hr = moment().tz("Asia/Hong_Kong").format('HH');
I can then proceed to write a function to calculate the difference between the 2 timezones in hours. I was hoping for a simpler method.
然后我可以继续编写一个函数来计算两个时区之间的时差(以小时为单位)。我希望有一个更简单的方法。
Is there a more elegant and simpler way to do it with moment library?
有没有更优雅、更简单的方法来使用时刻库?
回答by Amadan
Not sure about "simpler", but more correct (since not all timezones are a full hour from each other):
不确定“更简单”,但更正确(因为并非所有时区彼此相距整整一小时):
// 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>