Can I override the system time zone in Ruby?

I am here on Ubuntu 12.04 and I see:

$ cat /etc/timezone America/Phoenix 

Accordingly, Time will return time with a non-UTC zone:

 $ irb > Time.now => 2013-03-27 13:44:49 -0700 > Time.at 0 => 1969-12-31 17:00:00 -0700 

I can override the system time zone using the TZ environment variable:

 $ TZ=UTC irb > Time.now => 2013-03-27 20:47:19 +0000 > Time.at 0 => 1970-01-01 00:00:00 +0000 

Anyway, can I make this change programmatically, as part of the Ruby process?

+8
timezone ruby environment-variables
source share
3 answers

You can also set environment variables from ruby ​​by accessing the ENV hash:

 ENV['TZ'] = 'UTC' Time.at 0 #=> 1970-01-01 00:00:00 +0000 

also see this answer: Set the timezone offset in Ruby , It provides a way to write something like

 with_time_zone 'UTC' do # do stuff end # now TZ is reset to system standard 
+8
source share

You can use Time#gmtime . for example

 Time.now # => Wed Mar 27 16:55:11 -0400 2013 Time.now.gmtime # => Wed Mar 27 20:55:14 UTC 2013 Time.at(0) # => Wed Dec 31 19:00:00 -0500 1969 Time.at(0).gmtime # => Thu Jan 01 00:00:00 UTC 1970 

Time#utc also works and is an alias for Time#gmtime

+1
source share

ActiveSupport offers a lot of good quality related to TimeZone, depending on the use case.

 $ gem install activesupport $ irb > require 'active_support/time' # => true > Time.zone = 'Pacific Time (US & Canada)' # => "Pacific Time (US & Canada)" > Time.zone.now # => Wed, 27 Mar 2013 16:14:19 PDT -07:00 

ActiveSupport may be more addictive than you want, but you should not ignore it.

+1
source share

All Articles