In Rails, how do I convert and print a time to a different time zone?
I have a variable, start_time:
(rdb:5) start_time.class
ActiveSuppo开发者_如何学JAVArt::TimeWithZone
(rdb:5) start_time
Tue, 23 Feb 2010 14:45:00 EST -05:00
(rdb:5) start_time.in_time_zone(ActiveSupport::TimeZone::ZONES_MAP["Pacific Time (US & Canada)"]).zone
"PST"
(rdb:5) start_time.in_time_zone(ActiveSupport::TimeZone::ZONES_MAP["Pacific Time (US & Canada)"]).to_s(:time)
"2:45 PM ET"
I'd like to change 'to_s(:time)' so that it outputs the time in whatever zone is specified in the variable, not the default system time. I.e. The output would be "11:45 AM PT". How do I do this?
I think you want to create a TimeZone
object, and use its at()
method:
start_time = Time.now
start_time.rfc822 # => "Tue, 23 Feb 2010 10:58:23 -0500"
pst = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
pst.at(start_time).strftime("%H:%M %p %Z") # => "08:00 AM PST"
I ran into this issue recently and was able to solve it by essentially overriding the .to_s
option that I was using. I created an initializer called time_formats.rb and added the following line to it.
Time::DATE_FORMATS[:time_in_zone] = "%H:%M %p"
then changed (:time)
to (:time_in_zone)
like so...
start_time.in_time_zone(...your timezone here...]).to_s(:time_in_zone)
It should give you the time in the zone you are specifying. My environment is in UTC, so maybe that had something to do with it...
Given Beerlington's comments, I ended up adding the following (which is similar to the Proc defined for Time::DATE_FORMATS[:time]
:time_in_zone => lambda { |time|
time = time.strftime("%I:%M %p %Z").gsub(/([NAECMP])([DS])T$/, '\1T')
time = time[1..-1] if time =~ /^0/ # drop leading zeroes
time
}
精彩评论