Time.use_zone is not working as expected

核能气质少年 提交于 2019-12-18 12:53:20

问题


So right now it is 2:54 PM PST in San Francisco. For some reason, this code block is not returning 12:54 PM HST in Hawaii. Am I missing something here? I would expect this code to return me the current time in Hawaii

Time.use_zone('Hawaii') do
  Time.now
end
# => 2012-01-03 14:54:54 -0800 

回答1:


This should work ok:

Time.use_zone('Hawaii') do
  p Time.zone.now
end



回答2:


Try using Time.now.in_time_zone inside your block instead.

> Time.use_zone('Hawaii') do
>   Time.now.in_time_zone
> end
 => Tue, 03 Jan 2012 13:07:06 HST -10:00 



回答3:


Use Time.current if you want now with timezone support. Time.now is dangerous when working in a timezone aware application, as a rule of thumb I never use Time.now, only Time.current. Rails time helpers like 2.hours.ago and 4.days.from_now are based off of Time.current as well.

Also, this is a great article with a great cheat sheet at the bottom: http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails




回答4:


Time.now - using server time
Time.zone.now - using rails application time (in config: config.time_zone)
Time.use_zone - using 'your' timezone for given block


This example is wrong, because Time.now get time in your server timezone and with method in_time_zone translate time into an equivalent time in Hawaii timezone. But it's no current Time in Hawaii! It's your server time with utc offset for Hawaii.

Time.use_zone('Hawaii') do
  Time.now.in_time_zone
end
=> Wed, 14 Aug 2013 10:33:18 HST -10:00 

Time.now.in_time_zone
=> Thu, 15 Aug 2013 00:32:30 MSK +04:00 

For getting time in Hawaii timezone you must use

Time.use_zone('Hawaii') do
  Time.zone.now
end


来源:https://stackoverflow.com/questions/8719778/time-use-zone-is-not-working-as-expected

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