在Rails 3中放置时间格式规则的位置?

我发现自己重复输入我定义的许多strftime。

看过Ryan Bates的railscasts ep 32/33(我想),我在Time.now.to_s中为to_s方法创建了一个自定义选项,这样我就可以做Time.now.to_s(:sw),其中:sw是我的自定义方法,例如检索“2010年9月23日,下午5:00”。

但问题是,我不知道把#sw的定义放在哪里。 它应该在初始化文件夹中的文件中吗? 或者它应该进入application.rb?

谢谢!

我有一个文件config/initialisers/time_formats.rb包含:

 ... Time::DATE_FORMATS[:posts] = "%B %d, %Y" Time::DATE_FORMATS[:published] = "%B %Y" ... 

您只需重新启动服务器即可获取更改。

在locales文件中使用“time”而不是“date”,因为Rails时间戳是日期时间。

config / locales / en.yml中

 en: time: formats: default: "%Y/%m/%d" short: "%b %d" long: "%B %d, %Y" 

app / views / posts / show.html.haml中

  = l post.updated_at = l post.created_at, :format => :long 

使用Rails I18n API。

 # config/locales/en.yml en: date: formats: default: "%Y-%m-%d" short: "%b %d" long: "%B %d, %Y" # in views = l post.updated_at # will use default format of date in locales yml file 

看看I18n API

请阅读这篇文章:

Rails – to_formatted_s

使用名称创建文件:config / initializers / time_formats.rb

 Time::DATE_FORMATS[:my_custom_time_format] = "%Y-%m-%d %H:%M" 

你可以使用:

 formated_date = my_date.to_formatted_s(:my_custom_time_format) 

注意:您必须重新启动rails服务器(WEBRick,FCGI等)