Search code examples
ruby-on-railsrubyactivesupport

Specify UTC Offset instead of timezone to ActiveSupport::TimeWithZone


With ActiveSupport::TimeWithZone I'm able to do the following and get back a TimeWithZone object in the correct timezone.

Time.current.in_time_zone('Alaska')
:> Thu, 19 Oct 2017 08:45:08 AKDT -08:00

Is there an equivalent method to in_time_zone where I can pass it the UTC Offset in seconds and get back a TimeWithZone object with the specified offset?

offset = -25200 # -25200 seconds == -08:00
Time.current.in_utc_offset(offset)
:> Thu, 19 Oct 2017 08:45:08 -08:00

Thanks in advance!

Using Rails 5.1.2 & Ruby 2.4.1


Solution

  • Yes it is in vanilla Ruby: #getlocal(sec). It is not going to give you an ActiveSupport::TimeWithZone but it will give you the Time which you can format or do whatever you want with it, including using ActiveSupport extensions.

    2.4.1 :016 > Time.now.getlocal(3600)
    => 2017-10-19 22:56:45 +0100 
    2.4.1 :017 > Time.now.getlocal(-3600)
    => 2017-10-19 20:56:48 -0100 
    

    PS: -25200 is 7 hours in seconds :) -8:00 would be 28800