Are you still using `#strftime`
25 Sep 2018If you are a RoR developer, you may have used(or still using) the method strftime
to format time objects.
[6] pry(main)> t = Time.now
=> 2018-09-24 14:43:48 +0530
[7] pry(main)> t.strftime("%m/%d/%Y %I:%M%p")
=> "09/24/2018 02:43PM"
Its quite easy. right? Oh wait.
Have you ever tried to_formatted_s
. (aliased to to_s
)
[18] pry(main)> time = Time.now
=> 2018-09-24 14:46:40 +0530
[19] pry(main)> time.to_formatted_s(:time)
=> "14:46"
[20] pry(main)> time.to_formatted_s(:short)
=> "24 Sep 14:46"
[21] pry(main)> time.to_formatted_s(:long)
=> "September 24, 2018 14:46"
Here is the list of built-in formats you can use.
[1] pry(main)> Time::DATE_FORMATS
=> {:db=>"%Y-%m-%d %H:%M:%S",
:number=>"%Y%m%d%H%M%S",
:nsec=>"%Y%m%d%H%M%S%9N",
:time=>"%H:%M",
:short=>"%d %b %H:%M",
:long=>"%B %d, %Y %H:%M",
:long_ordinal=>#<Proc:0x00560829f4ec00@/....2.7.1/lib/active_support/core_ext/time/conversions.rb:12 (lambda)>,
:rfc822=>#<Proc:0x00560829f4ebd8@/...._ext/time/conversions.rb:16 (lambda)>,
:iso8601=>#<Proc:0x00560829f4ebb0@/....re_ext/time/conversions.rb:20 (lambda)>}
You can have your own time formats.
# config/initializers/time_formats.rb
Time::DATE_FORMATS.merge!(
report: '%-m/%-d/%Y %H:%M %p %z',
client: '%B %d, %Y %H:%M %p %z'
)
[7] pry(main)> Time.now.to_s(:report)
=> "9/24/2018 15:57 PM +0530"
[8] pry(main)> Time.now.to_s(:client)
=> "September 24, 2018 15:57 PM +0530"