Rails: the difference between time zones in hours

I would like to say user1 is 4 hours ahead of user2 , calculated based on the time zones that users have specified in their account.

Using the following code:

 time1 = Time.zone.now.in_time_zone(user1.time_zone) time2 = Time.zone.now.in_time_zone(user2.time_zone) distance_of_time_in_words time1,time2 

... gives a difference less than a minute - similarly subtracting it twice gives 0 . Rails, obviously, still sees these two times the same.

Any idea how I can calculate this difference between two time zones?

+4
source share
1 answer

If you take an instance of time1 and call utc_offset on it, you will get the amount of time offset from UTC in seconds. Combine this with utc_offset of time2 , enter some subtraction, and you should get the time difference in seconds. From there, you can make a conversation at any point in time that you like.

 irb(main):020:0> time1 = Time.zone.now.in_time_zone("EST") => Sun, 09 Jun 2013 07:11:46 EST -05:00 irb(main):021:0> time2 = Time.zone.now.in_time_zone("MST") => Sun, 09 Jun 2013 05:11:49 MST -07:00 irb(main):022:0> time_difference_in_seconds = time2.utc_offset - time1.utc_offset => -7200 irb(main):025:0> (time_difference_in_seconds/60/60).abs => 2 
+5
source

Source: https://habr.com/ru/post/1485279/


All Articles