Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

3.7. Converting Between Time Zones

Problem

You want to change a time object so that it represents the same moment of time in some other time zone.

Solution

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 and DateTime objects.

The Time#gmtime method modifies a Time object in place, converting it to UTC. The 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

The 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 offset:

	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 DateTime 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 to call offset on a DateTime object known to be in local time. The offset will usually be a rational number with a denominator of 24:

 local = DateTime.now utc = local.new_offset local.offset # => Rational(-5, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required