Figuring out the local timezone in Ruby on OSX

Eric PughApril 9, 2007

I am starting to hit some of the odd corners of Ruby. For example, I want to know what the local timezone of my Mac is. I can run and parse the output, but unfortunately I get back EDT, and the TZinfo library cant parse that because its not a standard timezone, throwing an TZInfo::InvalidTimezoneIdentifier.

I did discover however that on OSX the file /etc/localtime is sym-linked to the correct timezone file! When I did ls -l /etc/localtime I got back /usr/share/zoneinfo/US/Eastern, which gives me something to parse that TZInfo will understand.

Below is my unit test that demonstrates my progress in hacking to a solution! Hopefully this will help anyone else.

My solution is very brittle, but should work for now. Anyone have a better suggestion, please speak up!!!

def test_getting_local_timezone
t =
assert_equal `EDT, t.strftime(`%Z)

assert_raise(TZInfo::InvalidTimezoneIdentifier) { Timezone.get(`EDT)}

result = %x[ls -l /etc/localtime]
puts result

assert_match '/etc/localtime -> /usr/share/zoneinfo/US/Eastern', result, 'Make sure we get back US/Eastern. This only works when you are in US/Eastern Timezone!'

string = 'lrwxr-xr-x 1 root wheel 30 Jan 17 20:38 /etc/localtime -> /usr/share/zoneinfo/US/Eastern'
split = string.split('/')
assert_equal 8, split.size
timezone = '#{split[split.size-2]}/#{split.last}'
assert_equal 'US/Eastern', timezone


More blog articles:

We empower great search teams!

We help teams that use Solr and Elasticsearch become more capable through consulting and training.

Services Training