Blog

Figuring out the local timezone in Ruby on OSX

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 Time.now 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_timezonet = Time.nowassert_equal `EDT, t.strftime(`%Z)assert_raise(TZInfo::InvalidTimezoneIdentifier) { Timezone.get(`EDT)}result = %x[ls -l /etc/localtime]puts resultassert_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.sizetimezone = '#{split[split.size-2]}/#{split.last}'assert_equal 'US/Eastern', timezoneend