开发者

Set time zone offset in Ruby

The default time zone offset in Ruby is apparently -0800. I want开发者_如何学JAVA to set mine to -0500. How do I do this?


Set the TZ environment variable...

$ ruby -e 'puts Time.now'
Sat Jan 15 20:49:10 -0800 2011
$ TZ=UTC ruby -e 'puts Time.now'
Sun Jan 16 04:49:20 +0000 2011

Ruby gets the time zone information from the host's operating system.

Most directly, it uses a C library API specified by C99 and Posix.

The implementation of that API is system-specific, on my Mac that means it consults /etc/localtime unless there is a TZ environment variable.

It's about the same on Linux.


updated answer: use ActiveSupport

The more recent releases of Rails's ActiveSupport module offer a MUCH better solution in the active_support/time module. (Note that modules in ActiveSupport can be loaded without dragging in all of Rails...)

I recommend this approach since it doesn't require setting any global state (e.g. setting the time zone on your OS or modifying ENV['TZ']) that might have unexpected side effects elsewhere. Here's how you use it:

>> require 'active_support/time'
=> true
>> Time.at(1000000000).in_time_zone('US/Eastern')
=> Sat, 08 Sep 2001 21:46:40 EDT -04:00
>> Time.at(1000000000).in_time_zone('US/Pacific')
=> Sat, 08 Sep 2001 18:46:40 PDT -07:00

PS: if you want to see all of the time zone names supported, you can refer to:

>> ActiveSupport::TimeZone::MAPPING
=> => {"International Date Line West"=>"Pacific/Midway", "Midway Island"=>"Pacific/Midway", ...}

(original answer -- now outdated)

A bit late to the party, but found that I needed to set the time zone to different values according to user data.

What I used to do was (but see update below):

def with_time_zone(tz_name)
  prev_tz = ENV['TZ']
  ENV['TZ'] = tz_name
  yield
ensure
  ENV['TZ'] = prev_tz
end

Which permits things like:

>> with_time_zone('US/Eastern') { puts Time.at(1000000000) }
2001-09-08 21:46:40 -0400
>> with_time_zone('US/Pacific') { puts Time.at(1000000000) }
2001-09-08 18:46:40 -0700


To programmatically set the ruby time zone, 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

This helps to avoid the need to modify your OS just for an app, and gives you more portability of your app if you move it to a different machine. If you're using Rails, ActiveSupport::TimeZone also offers some functionality to help with overriding the TimeZone.


Change the time zone on your OS; Ruby will pick up the change.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜