简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM