The Spaghetti Refactory Established 2015

A Primer on Time Zone parsing in Rails with ActiveSupport

To get time zone abbreviation (ie ‘PST’ for Pacific Time), you can call #zone method on any Time object. However, ActiveSupport::TimeZone parsing does not work with that zone format, so if you need to parse a time object by zone, better to get the full zone name. Here’s a method that does that. 

This is a helper method for views, call by itself, not on an object:

def time_zone_name(any_time_object)
utc_offset = time.to_s[-5..-1]
# UTC offset example: Eastern Time == '-0500'
# We need it in integer format -5
ActiveSupport::TimeZone[utc_offset.gsub!('0','').to_i].name
end

# => ‘Bogota’ (which is the same time zone as Eastern Standard Time (US and Canada)

Now you can use this time zone string to parse Time objects with ActiveSupport::TimeZone

ActiveSupport::TimeZone[“Bogota”].parse(Time.now.to_s)
# => outputs the current time with -0500 UTC offset, aka Eastern Time

Caveat: it will output that time with the abbreviation for Bogota time zone, COT. Example: Mon, 12 Jan 2015 15:50:57 COT -05:00 The time and UTC offset will be the same as for EST, and should behave similarly when parsing, but it is still something to be aware of.

Tags