2012-08-06 67 views
24

這裏是想什麼我顯示:格式化日期對象,以顯示人類可讀的日期

May 13, 2012 

這裏是正在顯示的內容:

2012-05-13 

我搜索了一些答案,並帶領我「Formatting Dates and Floats in Ruby」,在那裏它提到一個可能的解決方案:

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

然而,這並不改變第e輸出。沒有調試錯誤或異常被觸發。

我可以做到這一點和它的作品完美的罰款:

<p class="date"><%= Time.now.to_s("%B %d, %Y") %></p> 

這裏是我的移民文件(看到我用什麼樣的數據類型):

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

     t.date :postdate 

     t.timestamps 
    end 
    end 
end 

回答

44

Date.to_s是不一樣的Time.to_s 。你postdateDate,所以因此,你可能想在strftime尋找替代:

postdate.strftime("%B %d, %Y") 

甚至看向自己的自定義日期格式添加到您的Rails應用程序:
Need small help in converting date format in ruby

+0

又見 - http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime – JGrubb 2012-08-07 13:20:41

+8

一個小小的提示:'的strftime(「%B%-d ,%Y「)對於人的可讀性來說更好一些。 '%-d'刪除前導0,即2013年5月6日=> 2013年5月6日。 – 2013-11-15 04:14:33

29

to_formatted_s功能已經在Rails中有一些用於DateTime對象的常見人類可讀格式。

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" 
+5

,它被別名爲_to_s_。 – 2015-08-01 18:48:31