How to change the time zone on a TimeWithZone object?

I'm working on an app which has its config.time_zone = 'Kolkata' (which is UTC +5:30), I'm trying to save the time for a particular object in EST/EDT (UTC -5:00/-4:00) from the ActiveAdmin panel.

Since it involves daylight savings, I'd rather not resort to manual calculations and transform the ActiveSupport::TimeWithZone object from UTC +530 into UTC -400. Is it possible to just change the zone part of a TimeWithZone object without converting it?

P.S. I did come across this question. But it isn't have the answer I'm looking for.(one of the comments even mention it)

1

2 Answers

I've been scouring the internet for solutions to a similar problem that you've described and amazed that I couldn't find one. I eventually stumbled upon the TimeWithZone#change method when reading through the docs

So if you just want to adjust the Zone without changing the Time, you can do

time.change(zone: "Eastern Time (US & Canada)") 

and change it back to UTC again after the conversion if you like

time.change(zone: "Eastern Time (US & Canada)").in_time_zone("UTC") 

It is recommended that all datetime objects should always be stored in UTC -0000, as said here. If yet you want to convert it to do some calculations, use the utc_offset method or convert both objects to UTC by using the utc method, as seen here.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like