rwb rwb - 2 months ago 13x
Ruby Question

Ruby / Rails - How do i change the timezone of a Time, without changing the time

I have a record in the database which has


is a Time, with zone UTC - '2001-01-01 14:20:00', for example.
is a string - 'America/New_York', for example.

I want to create a new time object with
but whose timezone is
. I do not want to load the
and then convert to
, because Rails will be clever and update the time from UTC to be consistent with that timezone.

t = Foo.start_time
=> 2000-01-01 14:20:00 UTC
=> "UTC"
=> Sat, 01 Jan 2000 09:20:00 EST -05:00

Instead, i want to see

=> Sat, 01 Jan 2000 14:20:00 EST -05:00

ie. i want to say

=> 2000-01-01 14:20:00 UTC = "America/New_York"
=> "America/New_York"
=> 2000-01-01 14:20:00 EST


Sounds like you want something along the lines of'America/New_York').local_to_utc(t)

This says convert this local time (using the zone) to utc. If you have set then you can of course to

This won't use the timezone attached to t - it assumes that it's local to the time zone you are converting from.

One edge case to guard against here is DST transitions: the local time you specify may not exist or may be ambiguous.