Reputation: 827
I'd like to be able to say user1 is 4 hours ahead of user2
, calculated based on the time zones the users specify 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 of less than a minute
- similarly subtracting the two times gives 0
. Rails obviously still sees these two times as the same.
Any idea how I can calculate this difference between two time zones?
Upvotes: 6
Views: 5615
Reputation: 985
If you take your time1
instance and call utc_offset
on it, you will get the amount of time offset from UTC in seconds. Combine this with the utc_offset
of time2
, throw in some subtraction, and you should get the time difference in seconds. From there you can do the conversation to whatever unit of time 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
Upvotes: 8