Last Updated: February 25, 2016
·
734
· mikem

Create a Time in a specific timezone in Ruby

Have you ever wanted to use pure Ruby to get a Time instance in a specific timezone? Me too.

There are plenty of posts on the web on how to do this with ActiveSupport::TimeWithZone, but sometimes you want a small script which doesn't have any dependencies.

Ruby looks at the TZ environment variable to determine what timezone it should be operating in. Here's a small wrapper function that sets the timezone to what you want, performs the Time action you need, and restores the environment variable to its previous value.

require 'time'

def format_time time_str
  old_tz = ENV['TZ']

  return if time_str.nil?

  ENV['TZ'] = 'America/New_York'
  Time.parse time_str
ensure
  ENV['TZ'] = old_tz
end

Here's a sample session:

Time.parse 'Aug 04'
#=> 2014-08-04 00:00:00 -0700

format_time 'Aug 04'
#=> 2014-08-04 00:00:00 -0400

Time.parse 'Aug 04'
#=> 2014-08-04 00:00:00 -0700

ENV['TZ'] = 'Europe/Berlin'
#=> "Europe/Berlin"

Time.parse 'Aug 04'
#=> 2014-08-04 00:00:00 +0200

format_time 'Aug 04'
#=> 2014-08-04 00:00:00 -0400

Time.parse 'Aug 04'
#=> 2014-08-04 00:00:00 +0200

You can modify format_time above to take the target timezone as an argument and even the code you want to execute in the target timezone as a block.