Get timezone difference in hours with moment
17,475
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>
Author by
guagay_wk
Updated on June 26, 2022Comments
-
guagay_wk almost 2 years
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?
-
guagay_wk over 8 yearsUpvoted and selected as answer. I don't quite understand why the need for
var now = moment.utc();
? Why not just getNewYork_time_hr
offset ofHongKong_time_hr
? -
Amadan over 8 yearsThe comment above it was a hint - timezone offsets change throughout the year, and not all at the same time. The difference between Hong Kong (has no DST) and New York (has DST) is different depending on whether you're asking in summer or in winter. And you can't just use
hr
because, e.g. Calcutta is offset at +05:30. -
Matt Johnson-Pint over 8 yearsGreat answer. Though it will also work if you just pass
moment()
instead ofmoment.utc()
. It still gets evaluated as the same UTC-based timestamp regardless of which form you pass. +1 about the result being different depending on when you call it. "How many hours between New York and Los Angeles?" (Usually 3, but sometimes 2 and sometimes 4.) -
Matt Johnson-Pint over 8 yearsFYI, the other way to obtain an offset is
moment(now).tz("America/New_York").utcOffset()
, but either way is fine. You still have to subtract them manually.