Rails:时区之间的差异(以小时为单位)

编程入门 行业动态 更新时间:2024-10-23 23:33:01
本文介绍了Rails:时区之间的差异(以小时为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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 的偏移量.将其与 time2utc_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:关键词]

本文发布于:2023-04-30 12:37:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时区   差异   单位   小时   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!