Rails: Difference between timezones in hours

戏子无情 提交于 2019-12-10 16:47:01

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/17009239/rails-difference-between-timezones-in-hours

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!