You want to change a time object so that it represents the same moment of time in some other time zone.
The most common time zone conversions are the conversion of
system local time to UTC, and the conversion of UTC to local time.
These conversions are easy for both
Time#gmtime method modifies a
Time object in place, converting it to UTC.
Time#localtime method converts
in the opposite direction:
now = Time.now # => Sat Mar 18 20:15:58 EST 2006 now = now.gmtime # => Sun Mar 19 01:15:58 UTC 2006 now = now.localtime # => Sat Mar 18 20:15:58 EST 2006
DateTime.new_offset method converts a
DateTime object from one time zone
to another. You must pass in the dstination time zone's offset from
UTC; to convert local time to UTC, pass in zero. Since
DateTime objects are immutable, this method
creates a new object identical to the old
DateTime object, except for the time zone
require 'date' local = DateTime.now local.to_s # => "2006-03-18T20:15:58-0500" utc = local.new_offset(0) utc.to_s # => "2006-03-19T01:15:58Z"
To convert a UTC
object to local time, you'll need to call
DateTime#new_offset and pass in the numeric
offset for your local time zone. The easiest way to get this offset is
offset on a
DateTime object known to be in local time.
The offset will usually be a rational number with a denominator of
local = DateTime.now utc = local.new_offset local.offset # => Rational(-5, ...