Can I override the system timezone in Ruby?

2019-02-21 21:07发布

I'm here on Ubuntu 12.04, and I can see:

$ cat /etc/timezone 
America/Phoenix

Accordingly Time will return a 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

Is there anyway I can make this change programmatically, within a Ruby process?

3条回答
何必那么认真
2楼-- · 2019-02-21 21:43

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

查看更多
唯我独甜
3楼-- · 2019-02-21 22:03

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.

查看更多
干净又极端
4楼-- · 2019-02-21 22:05

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 stuff
end

# now TZ is reset to system standard
查看更多
登录 后发表回答