Search code examples
ruby-on-railstimezoneactivesupport

How to get timezone in a shorter format


Time.zone.name gives "Eastern Time (US & Canada)". Is there a way to get the time zone for a Time object in a shorter format like EST?


Solution

  • Rails use tzinfo gem https://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html) , but the shortcode you are looking for is not provided. So there's no direct way to get it. Although the Time class does have a method called zone which returns the shortcode for a time of a given time zone. So I would do something like this if I was in your place:

    (Time.new.in_time_zone current_user.time_zone).zone
    (Time.new.in_time_zone "Eastern Time (US & Canada)").zone