Can I override the system timezone in Ruby?
You can also set environment variables from within ruby by accessing the ENV
hash:
ENV['TZ'] = 'UTC'Time.at 0#=> 1970-01-01 00:00:00 +0000
also see this answer: Set time zone offset in Ruby, It provides a way to write something like
with_time_zone 'UTC' do # do stuffend# now TZ is reset to system standard
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
Depending on the use case, ActiveSupport offers a lot of TimeZone related goodness.
$ 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 a larger dependency than you want, but you shouldn't overlook it.