如何计算Ruby中时区的时差

问题描述:

我想查看当前时间是否在中午(午餐)之后。如何计算Ruby中时区的时差

noon_time = Time.parse "12:00 pm" 
    current_time = Time.now 
    if current_time < noon_time 
    #eat a big meal or sleep its after lunch time 
    else 
    #work hard its not time to eat 
    end 

当我在9:38 pm运行这段代码时,它说“吃大餐”。

我是否需要做这样的事情并捕获用户为我的网站设置的时间?

offset = Time.now.in_time_zone(current_user.time_zone).gmt_offset/60/60 

你可以尝试从用户的角度解析时间:

Time.zone(current_user.time_zone).parse("12:00pm") 

如果使用Time.now你在这,想必,UTC默认时区使用。为您的用户模型制作一个包装方法time_current可能是一个好主意,它会在正确的时区返回时间?偏移量本身孤立是没有意义的。

你也可以做同样的事情time_parse,然后你的代码看起来像:

if current_user.time_current >= current_user.time_parse("12:00pm") 
    # ... Lunch time! 
end 

或者更简洁地说:

if current_user.time_current.hour >= 12 
    # ... Lunch time! 
end