Skip to content

Instantly share code, notes, and snippets.

@numist
Created November 13, 2014 17:48
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save numist/f34cb150e337a8b948d9 to your computer and use it in GitHub Desktop.
Get the system time zone in Olson format using Ruby
def get_local_timezone_str
# Yes, this is actually a shell script…
olsontz = `if [ -f /etc/timezone ]; then
cat /etc/timezone
elif [ -h /etc/localtime ]; then
readlink /etc/localtime | sed "s/\\/usr\\/share\\/zoneinfo\\///"
else
checksum=\`md5sum /etc/localtime | cut -d' ' -f1\`
find /usr/share/zoneinfo/ -type f -exec md5sum {} \\; | grep "^$checksum" | sed "s/.*\\/usr\\/share\\/zoneinfo\\///" | head -n 1
fi`.chomp
# …and it almost certainly won't work with Windows or weird *nixes
throw "Olson time zone could not be determined" if olsontz.nil? || olsontz.empty?
return olsontz
end
@numist
Copy link
Author

numist commented Nov 13, 2014

Olson time zone names are necessary for successful time and date work because both short codes and gmt offsets are ambiguous. One of the short codes refers to five different time zones1, and gmt offsets lose daylight savings time information that would differentiate otherwise identical time zones.

1 CST refers to Central Standard Time, China Standard Time, Central Standard Time (Australia), Central Summer Time (Australia), and Cuba Standard Time

@numist
Copy link
Author

numist commented Nov 13, 2014

When using Rails, things only get worse—Rails gets the time zone from its configuration, so it's not useful for fetching the system's time zone.

Adding to the dissonance, Rails cleverly extends Time:

% rails console
Loading development environment (Rails 4.1.7)
irb(main):001:0> Time.now.zone
=> "PST"
irb(main):005:0> Time.now.zone.class
=> String
irb(main):002:0> Time.zone
=> #<ActiveSupport::TimeZone:0x00000101dae2b8 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffset: 0,0,UTC>>>>
irb(main):003:0> 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment