Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 705
guagay_wk Avatar asked Nov 13 '15 01:11

guagay_wk


People also ask

How do you find the hour difference in moments?

To get the hour difference between two times with moment. js, we can use the duration , diff , asHours and asMinutes methods. For instance, we can write: const startTime = moment("12:26:59 am", "HH:mm:ss a"); const endTime = moment("06:12:07 pm", "HH:mm:ss a"); const duration = moment.

How do you get moments from time zone?

var tz = moment. tz. guess(); It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

How do you use tz in a moment?

For example, if you parse the string '2020/01/02' and then call the moment#tz() method, you're telling moment to parse the string in the locale time, and then convert the date to a given IANA timezone. // '20200101 21:00 PST' moment('2020/01/02', 'YYYY/MM/DD'). tz('America/Los_Angeles'). format('YYYYMMDD HH:mm z');

How do you add timezone offset in moment?

If you are wanting to set the offset globally, try using moment-timezone. Note that once you set an offset, it's fixed and won't change on its own (i.e there are no DST rules). If you want an actual time zone -- time in a particular location, like America/Los_Angeles , consider moment-timezone. moment().


1 Answers

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>
like image 80
Amadan Avatar answered Sep 29 '22 08:09

Amadan