Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

javascript - Get timezone difference in hours with 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...