This takes advantage of the fact that Time#asctime
doesn't include the zone.
Given a time:
>> time = Time.now
=> 2013-03-13 13:01:48 -0500
Force it to another zone (this returns an ActiveSupport::TimeWithZone
):
>> ActiveSupport::TimeZone['US/Pacific'].parse(time.asctime)
=> Wed, 13 Mar 2013 13:01:48 PDT -07:00
Note that the original zone is ignored completely. If I convert the original time to utc, the result will be different:
>> ActiveSupport::TimeZone['US/Pacific'].parse(time.getutc.asctime)
=> Wed, 13 Mar 2013 18:01:48 PDT -07:00
You can use to_time
or to_datetime
on the result to get a corresponding Time
or DateTime
.
This question uses an interesting approach with DateTime#change
to set the tz offset. (Remember that ActiveSupport makes it easy to convert between Time
and DateTime
.) The downside is that there's no DST detection; you have to do that manually by using TZInfo's current_period
.