格式化时间戳
如何以更易读的格式格式化Rails时间戳? 如果我只是在我的视图中打印出created_at
或updated_at
,如下所示:
然后我会得到:
2009-03-27 23:53:38 UTC
strftime
(来自Ruby的时间)和to_formatted_s
(来自Rails的ActiveSupport)函数应该能够处理所有时间格式化需求。
看看I18n的function。 它允许您在视图中执行以下操作:
<%= localize(scenario.created_at, :format => :long) %>
在您的语言环境中定义格式的位置。 更多信息
也
<%= l scenario.created_at, :format => :sample) %>
在locales / en.yml(取决于语言)
en: time: formats: sample: '%d.%m.%Y'
要了解更多信息,请参阅 – http://guides.rubyonrails.org/i18n.html
Time.now()。to_i效果很好。 对于反向转换,请使用Time.at(参数)
您可以使用strftime
以多种方式格式化时间戳。 我更喜欢some_data[:created_at].strftime('%F %T')
。 %F
显示“2017-02-08”(日历日期延长), %T
显示“08:37:48”(本地时间延长)。
对于时区问题,请将此行添加到config/application.rb
文件中
config.time_zone = 'your_timezone_string' config.active_record.default_timezone = :local
你必须修改时间戳文件,在我的例子中,这个文件位于/usr/local/rvm/gems/ruby-2.0.0-p195/gems/activerecord-4.2.0/lib/active_record/timestamp.rb
。 您必须搜索此行:
self.class.default_timezone == :utc ? Time.now.utc : Time.now
并将其更改为:
self.class.default_timezone == :utc ? Time.now.utc : Time.now.strftime('%Y-%m-%d %H-%M-%S')
诀窍是使用strftime
方法修改格式,您可以根据需要更改格式。
现在rails将使用您的格式更新“updated_at”列。