格式化日期对象以显示人类可读日期

ser*_*erg 35 ruby format ruby-on-rails date

这是我想要展示的内容:

May 13, 2012
Run Code Online (Sandbox Code Playgroud)

这是显示的内容:

2012-05-13
Run Code Online (Sandbox Code Playgroud)

我搜索了一些答案,它引导我" 在Ruby中格式化日期和浮动 ",它提到了一个可能的解决方案:

<p class="date"><%= @news_item.postdate.to_s("%B %d, %Y") %></p>
Run Code Online (Sandbox Code Playgroud)

但是,这根本不会改变输出.没有调试错误或异常被触发.

我可以做到这一点,它完美无缺:

<p class="date"><%= Time.now.to_s("%B %d, %Y") %></p>
Run Code Online (Sandbox Code Playgroud)

这是我的迁移文件(查看我使用的数据类型):

class CreateNewsItems < ActiveRecord::Migration
  def change
    create_table :news_items do |t|

      t.date :postdate

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

Cas*_*per 54

Date.to_s是不一样的Time.to_s.你postdate是一个Date,所以你可能想看一下strftime:

postdate.strftime("%B %d, %Y")
Run Code Online (Sandbox Code Playgroud)

甚至可以在Rails应用程序中添加自己的自定义日期格式:
在ruby中转换日期格式需要一些帮助

  • 一个小注:`strftime("%B%-d,%Y")`对于人类可读性来说更好一点.`%-d`删除了前导0,即2013年5月6日=> 2013年5月6日. (10认同)

Fer*_*her 42

to_formatted_s功能已经有一些共同的人类可读的格式DateTime在Rails的对象.

datetime.to_formatted_s(:db)            # => "2007-12-04 00:00:00"
datetime.to_formatted_s(:short)         # => "04 Dec 00:00"
datetime.to_formatted_s(:long)          # => "December 04, 2007 00:00"
datetime.to_formatted_s(:long_ordinal)  # => "December 4th, 2007 00:00"
datetime.to_formatted_s(:rfc822)        # => "Tue, 04 Dec 2007 00:00:00 +0000"
datetime.to_formatted_s(:iso8601)       # => "2007-12-04T00:00:00+00:00"
Run Code Online (Sandbox Code Playgroud)

  • 别名为_to_s_. (6认同)

Sun*_*que 8

<%= time_ago_in_words @user.created_at %>
Run Code Online (Sandbox Code Playgroud)

结果: 9 小时前