Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default Ruby Time format

I keep having to append ".strftime("%H:%M")" to anything that is displaying a time in my Rails project. I have a start time and an end time for each Concert object, so I have to append ".strftime("%H:%M")" whenever I wanna display those times.

Note that I'm not asking to change the date format. The date looks fine as it is (as MM/DD/YYYY).

What's the best way to get around this? Is there a way to set the default time format?

(I'm pretty sure this is only a Ruby thing, but I'm a newbie, so I'm not sure.)

like image 246
user5243421 Avatar asked Jan 12 '11 23:01

user5243421


3 Answers

Since you're using Rails, take advantage of the I18n support: http://guides.rubyonrails.org/i18n.html#adding-date-time-formats

# config/locales/en.yml
en:
  time:
    formats:
      default: "%H:%M"

Then when you call I18n.l Time.now or <%= l Time.now %>, it'll use that format automatically.

like image 154
coreyward Avatar answered Sep 19 '22 01:09

coreyward


Ruby on Rails has built-in presets for formatting Date and Time instances. Here's what they are for Time on my machine:

>> Time::DATE_FORMATS
=> {:short=>"%d %b %H:%M", :db=>"%Y-%m-%d %H:%M:%S", :rfc822=>#<Proc:0x0000000103700b08@/Users/donovan/.gem/gems/activesupport-3.0.1/lib/active_support/core_ext/time/conversions.rb:13>, :time=>"%H:%M", :number=>"%Y%m%d%H%M%S", :long_ordinal=>#<Proc:0x0000000103700e50@/Users/donovan/.gem/gems/activesupport-3.0.1/lib/active_support/core_ext/time/conversions.rb:12>, :long=>"%B %d, %Y %H:%M"}

You can easily use them like so:

>> Time.now.to_s(:db)
=> "2011-01-12 15:26:11"

You can define your own and use it, too:

>> Time::DATE_FORMATS[:mine] = "%H:%M"
=> "%H:%M"
>> Time.now.to_s(:mine)
=> "15:28"
like image 39
Brian Donovan Avatar answered Sep 21 '22 01:09

Brian Donovan


You could create a custom function in your application_helper.rb file. Maybe something like:

def custom_time(date)
  date.strftime("%H:%M")
end

Not sure if this is best practice but it should work well.

like image 29
JackCA Avatar answered Sep 22 '22 01:09

JackCA