问题描述
限时送ChatGPT账号..我希望能够说 user1 比 user2 早 4 小时
,这是根据用户在其帐户中指定的时区计算得出的.
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.
使用以下代码:
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
...给出不到一分钟
的差异 - 类似地减去两次给出0
.Rails 显然仍然认为这两次是相同的.
...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?
推荐答案
如果你拿你的 time1
实例并在它上面调用 utc_offset
,你会得到时间量以秒为单位与 UTC 的偏移量.将其与 time2
的 utc_offset
结合起来,加上一些减法,你应该得到以秒为单位的时间差.从那里你可以按照你喜欢的任何时间单位进行对话.
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
这篇关于Rails:时区之间的差异(以小时为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论