本文介紹了以小時為單位獲取時區差異的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想通過 Node.js moment 模塊獲取紐約和香港之間的時區差異.我已經做了一些前期工作.
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.
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?
推薦答案
不確定更簡單",但更正確(因為并非所有時區都相隔一小時):
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>
這篇關于以小時為單位獲取時區差異的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!