2017-11-18 49 views
0

我想查看當前時間是否在中午(午餐)之後。如何計算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 

回答

1

你可以嘗試從用戶的角度解析時間:

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