Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how get current time zone (Time.zone) in a format that can be used with ActiveSupport::TimeZone[zone].parse()?

How can a method take the current Time.zone and put it into a format that is usable by ActiveSupport::TimeZone[some_zone].parse()?

It seems very strange that Time.zone.to_s returns a string that can not be used with ActiveSupport::TimeZone[zone].parse()

Time.zone.to_s returns "(GMT-08:00) Pacific Time (US & Canada)"

But ActiveSupport::TimeZone["(GMT-08:00) Pacific Time (US & Canada)"] is nil.

ActiveSupport::TimeZone["(GMT-08:00) Pacific Time (US & Canada)"] => nil  ActiveSupport::TimeZone["Pacific Time (US & Canada)"] => (GMT-08:00) Pacific Time (US & Canada) 
like image 455
jpw Avatar asked Dec 14 '12 23:12

jpw


People also ask

How do I find time zones in rails?

In Rails, to see all the available time zones, run: $ rake time:zones:all * UTC -11:00 * American Samoa International Date Line West Midway Island Samoa * UTC -10:00 * Hawaii * UTC -09:00 * Alaska ... The default time zone in Rails is UTC.


1 Answers

Use Time.zone.name, not Time.zone.to_s

[1] pry(main)> Time.zone.to_s => "(GMT-05:00) Eastern Time (US & Canada)" [2] pry(main)> Time.zone.name => "Eastern Time (US & Canada)" [3] pry(main)> ActiveSupport::TimeZone[Time.zone.name] => (GMT-05:00) Eastern Time (US & Canada) 

As for how I got this (as requested), I just know the name method exists on Time.zone. If I didn't know this by heart though, I will check the docs. If it's not in there as you say (and it is, here), I typically inspect the class/module/object with Pry. Pry is an alternative to irb that lets me do something like

[1] pry(main)> cd Time.zone [2] pry(#<ActiveSupport::TimeZone>):1> ls -m Comparable#methods: <  <=  ==  >  >=  between? ActiveSupport::TimeZone#methods: <=>  =~  at  formatted_offset  local  local_to_utc  name  now  parse  period_for_local  period_for_utc  to_s  today  tzinfo  utc_offset  utc_to_local self.methods: __pry__ [3] pry(#<ActiveSupport::TimeZone>):1> name => "Eastern Time (US & Canada)" 

ls -m on line [2] above prints methods on the object (if you scroll right you'll see name listed there). You can see in [3] I can call name directly on the Time.zone object I'm inside of and get the output you're looking for.

like image 102
deefour Avatar answered Oct 05 '22 23:10

deefour