In Rails, how do I convert and print time to a different time zone?

I have a variable, start_time:

(rdb:5) start_time.class ActiveSupport::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 would like to change 'to_s (: time)' so that it displays the time in any zone specified in the variable, and not by default. That is, the output will be "11:45 AM PT." How to do it?

+4
source share
3 answers

I recently ran into this problem and was able to solve it, essentially overriding the .to_s option that I used. I created an initializer called time_formats.rb and added the following line to it.

 Time::DATE_FORMATS[:time_in_zone] = "%H:%M %p" 

and then changed (:time) to (:time_in_zone) so ...

 start_time.in_time_zone(...your timezone here...]).to_s(:time_in_zone) 

He should give you time in the zone that you indicate. My environment is in UTC, so maybe something has to do with it ...

+2
source

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" 
+3
source

Given Beerlington's comments, I added the following (similar to 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 } 
0
source

Source: https://habr.com/ru/post/1302086/


All Articles