在rails中的模型中格式化日期时间

Viv*_*thi 3 methods formatting model ruby-on-rails date

我有一个视图,它将日期时间打印为#{@ event.starts_at.strftime("%m /%d /%Y%H:%M")}.所以每次我打印starts_at时,我都必须在视图中使用strftime.我需要找到一种方法来为我的'event'模型添加一个方法,这样每次打印event.starts_at或event.method_name(starts_at)时都会自动格式化日期

Fer*_*Fer 6

你可以覆盖getter,如下所示:

class Event < ActiveRecord::Base
  def starts_at
    attributes['starts_at'].strftime("%m/%d/%Y %H:%M")
  end
end
Run Code Online (Sandbox Code Playgroud)

考虑到必须使用字符串而不是符号作为属性哈希.

这样说,如果你的应用程序试图获得国际化,这会锁定你,因为时间格式因地区而异

您可以使用导轨I18n:

de.yml

de:
  time:
    formats: 
      default: '%A, %d. %B %Y, %H:%M Uhr'
      long: '%A, %d. %B %Y, %H:%M Uhr'
      short: '%d. %B, %H:%M Uhr'
      very_short: '%d.%m.%Y, %H:%M Uhr'
Run Code Online (Sandbox Code Playgroud)

有了它你可以使用:

> I18n.localize Event.first.starts_at, format: :very_short
# => "26.11.2012, 10:35 Uhr"
Run Code Online (Sandbox Code Playgroud)

localize方法别名I18n.l

它将使用正确的(如果定义)