ruby get Time in given timezone

前端 未结 9 1139
情书的邮戳
情书的邮戳 2020-12-28 13:17

In ruby, how can I get current time in a given timezone? I know the offset from UTC, and want to get the current time in the timezone with that offset.

相关标签:
9条回答
  • 2020-12-28 13:52

    For an UTC offset of x hours, the current time can be calculated with the help of ActiveSupport in Rails, as the others said:

    utc_offset = -7
    zone = ActiveSupport::TimeZone[utc_offset].name
    Time.zone = zone 
    Time.zone.now
    

    or instead of the two lines

    DateTime.now.in_time_zone(zone)
    

    Or, if you do not have Rails, one can also use new_offset to convert a locate DateTime to another time zone

    utc_offset = -7
    local = DateTime.now
    local.new_offset(Rational(utc_offset,24))
    
    0 讨论(0)
  • 2020-12-28 13:58

    I'd use the ActiveSupport gem:

    require 'active_support/time'
    my_offset = 3600 * -8  # US Pacific
    
    # find the zone with that offset
    zone_name = ActiveSupport::TimeZone::MAPPING.keys.find do |name|
      ActiveSupport::TimeZone[name].utc_offset == my_offset
    end
    zone = ActiveSupport::TimeZone[zone_name]
    
    time_locally = Time.now
    time_in_zone = zone.at(time_locally)
    
    p time_locally.rfc822   # => "Fri, 28 May 2010 09:51:10 -0400"
    p time_in_zone.rfc822   # => "Fri, 28 May 2010 06:51:10 -0700"
    
    0 讨论(0)
  • 2020-12-28 14:02

    Just add or subtract the appropriate number of seconds:

    >> utc = Time.utc(2009,5,28,10,1)           # given a utc time
    => Thu May 28 10:01:00 UTC 2009
    >> bst_offset_in_mins = 60                  # and an offset to another timezone
    => 60
    >> bst = t + (bst_offset_in_mins * 60)      # just add the offset in seconds
    => Thu May 28 11:01:00 UTC 2009             # to get the time in the new timezone
    
    0 讨论(0)
提交回复
热议问题