Time.use_zone is not working as expected

后端 未结 5 2033
醉酒成梦
醉酒成梦 2020-12-31 02:12

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 c

相关标签:
5条回答
  • 2020-12-31 02:48

    Don't use Time.now this is using your local time zone instead use Time.current

    Time.use_zone('Hawaii') do
      p Time.current
    end
    
    0 讨论(0)
  • 2020-12-31 02:50

    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
    
    0 讨论(0)
  • 2020-12-31 02:52

    This should work ok:

    Time.use_zone('Hawaii') do
      p Time.zone.now
    end
    
    0 讨论(0)
  • 2020-12-31 03:05

    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

    0 讨论(0)
  • 2020-12-31 03:09

    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 
    
    0 讨论(0)
提交回复
热议问题