Get the system time zone in Olson format using Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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