22

如何将 Rails 时间戳格式化为更易于阅读的格式?如果我只是打印出来created_atupdated_at在我看来是这样的:

<% @created = scenario.created_at %>

然后我会得到:

2009-03-27 23:53:38 UTC

4

6 回答 6

24

strftime来自 Ruby 的 Time)和to_formatted_s(来自 Rails 的 ActiveSupport)函数应该能够处理您所有的时间格式化需求。

于 2009-03-29T01:42:06.040 回答
8

看看 I18n 功能。它允许您在视图中执行以下操作:

<%= localize(scenario.created_at, :format => :long) %>

格式是在您的语言环境中定义的。 更多信息

于 2011-04-28T07:54:18.577 回答
7

<%= l scenario.created_at, :format => :sample) %>

在 locales/en.yml 中(取决于语言)

  en:
    time:
      formats:
        sample: '%d.%m.%Y'

要了解更多信息,请参阅 - http://guides.rubyonrails.org/i18n.html

于 2012-05-22T13:35:42.117 回答
4

Time.now().to_i 效果很好。对于反向转换使用 Time.at(argument)

于 2011-04-28T07:20:02.540 回答
0

您可以使用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
于 2017-03-08T14:06:39.410 回答
-1

您必须修改时间戳文件,在我的情况下,此文件位于/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”列。

于 2015-09-18T14:11:43.700 回答