9

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?

davetapley
  • 17,000
  • 12
  • 60
  • 86
  • Your question is pretty vague. Don't overestimate the helpfulness some context would provide. – BM5k Mar 27 '13 at 23:24

3 Answers3

10

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
Community
  • 1
  • 1
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
1

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

oldergod
  • 15,033
  • 7
  • 62
  • 88
Ilya O.
  • 1,500
  • 13
  • 19
  • That's great for figuring out how to get UTC-based times, but it doesn't help when the needed timezone isn't UTC. – javawizard May 20 '15 at 03:24
0

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.

BM5k
  • 1,210
  • 10
  • 28