开发者

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.)


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.


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"


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.


I use an initializer: config/initializers/time_formats.rb which contains:

[Time, Date].map do |klass|
  klass::DATE_FORMATS[:app_date] = "%m/%d/%Y"
  klass::DATE_FORMATS[:app_month_and_year] = "%B %Y"
  klass::DATE_FORMATS[:app_abbrev_month_and_year] = "%b %Y"
  ...
end

Then I use Time.now.to_s(:app_date), etc based on how I want to display it. You could add Time::DATE_FORMATS[:default] = "%H:%M" to accomplish what you're trying to do. This is not internationalized though - for that, coreyward's answer is probably better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜