LovingRails LovingRails - 4 months ago 14
Ruby Question

How to show the timezone offset in Ruby on Rails?

I am using time_zone_select to save users timezones.

<div class="row">
<div class="panel panel-primary">

<div class="panel-heading">
<%= f.label :time_zone, "TimeZone*" %>
</div>

<div class="panel-body">
<%= f.time_zone_select :time_zone, nil, {}, { :class => 'form-control' } %>
</div>
</div>
</div>


The users timezones are saving successfully in a string.

>> userp.time_zone
=> "Chennai"


Now when I display the user timezone I want to display the timezone offset like this

(GMT+05:30) Chennai


This is view template but I am not able to manipulate the timezone since it's stored as a string.

<div>
<small>
<i class="fa fa-clock-o" aria-hidden="true"></i>
<span style="padding-left:1px">TimeZone:</span>
<%= @user.time_zone %>
</small>
</div>


Can someone guide me, how to display timezone with offset?

Answer

You can treat ActiveSupport::TimeZone as an array with ActiveSupport::TimeZone[named_zone], e.g.:

  <div>
    <small>
    <i class="fa fa-clock-o" aria-hidden="true"></i>
    <span style="padding-left:1px">TimeZone:</span>            
    <%= ActiveSupport::TimeZone[@user.time_zone].to_s %> <%= @user.time_zone %>
    </small>
  </div>  

You can test it in Rails console:

[6] pry(main)> ActiveSupport::TimeZone["Chennai"].to_s
=> "(GMT+05:30) Chennai"

Please take a note that if you don't use #to_s, you will get the TimeZone object, which is not what you want. You can see detailed implementation on Github.

Slightly related, If you wonder why this module can be treated as an array, it is because it implements the []() method.

Comments