How to get Rails to interpret a time as being in a specific time zone?

前端 未结 2 527
死守一世寂寞
死守一世寂寞 2021-01-17 00:58

In Ruby 1.8.7, how to set the time zone of a time?

In the following examples, my system time zone is PST (-8:00 hours from UTC)

Given a time (21 Feb 2011

相关标签:
2条回答
  • 2021-01-17 01:52

    So I think this will (almost) accomplish what you want:

    require 'time'
    t = "21 Feb 2011, 20:45"
    Time.parse(t)           # => Mon Feb 21 20:45:00 -0700 2011
    t += " -05:00"          # this is the trick
    Time.parse(t)           # => Mon Feb 21 18:45:00 -0700 2011
    

    It still returns the time based on your system time zone, but the actual time is the correct time that you are seeking.

    By the way, this is tested on 1.8.7-p334.

    0 讨论(0)
  • 2021-01-17 02:04

    In ruby 1.8.7 it doesn't appear to be very easy to do what are asking for according to the documentation:

    http://www.ruby-doc.org/core-1.8.7/classes/Time.html

    However in 1.9 it looks a lot easier by passing the timezone offset to the localtime() method on a Time object:

    http://www.ruby-doc.org/core/classes/Time.html#M000346

    UPDATE

    The offset for Time.zone is easy since its an object on its own: (This is in a Rails console)

    ruby-1.8.7-p248 :001 > Time.zone
     => #<ActiveSupport::TimeZone:0x103150190 @current_period=nil, @name="Central Time (US & Canada)", @tzinfo=#<TZInfo::TimezoneProxy: America/Chicago>, @utc_offset=nil> 
    ruby-1.8.7-p248 :002 > Time.zone.utc_offset
     => -21600 
    ruby-1.8.7-p248 :003 > Time.zone.formatted_offset
     => "-06:00" 
    
    0 讨论(0)
提交回复
热议问题