Sathishkumar Sathishkumar - 1 year ago 87
Ruby Question

How to add timezone with my timestamp?

I have timezone as string (like "(GMT+00:00) UTC", "(GMT+05:30) Chennai" and so on.). Also I have timestamp like Mon, 01 Aug 2016 17:00:00 UTC +00:00. I need to change timestamp time based on timezone. Also timezone in the timestamp should not be changed. Im using rails 4.0.0. On every try it tells strings cannot be converted. Could anyone please help on this.

Answer Source

First of all, you need to retrieve the time zone from your string:

tz_as_string = "(GMT+05:30) Chennai"
tz_name = tz_as_string[/(?<=\) ).*/] # ⇒ "Chennai"
tz_timezone = ActiveSupport::TimeZone::MAPPING[tz_name] #⇒ "Asia/Kolkata"

and, finally:

tz = tz_timezone
#⇒  #<ActiveSupport::TimeZone:0x000000107a91c0 @name="Asia/Kolkata", ...
Time.parse('Mon, 01 Aug 2016 17:00:00 UTC +00:00').in_time_zone tz
#⇒ Mon, 01 Aug 2016 22:30:00 IST +05:30
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download