2010-06-15 113 views
26

我似乎無法找到這個,我覺得它應該很容易。在Ruby on Rails的,我怎麼走:將日期時間轉換爲月,日和年?

2010-06-14 19:01:00 UTC 

,並把它變成

June 14th, 2010 

我不能只使用視圖中的助手?

+2

http://stackoverflow.com/questions/165170/in-ruby-在軌道上 - 如何做 - 我 - 格式 - 與 - 後綴 - 在 - 太陽 - oct - 5t – Anurag 2010-06-15 10:00:20

回答

49

我不知道

June 14th, 2010 

但是如果你想

June 14, 2010 

參考how do i get name of the month in ruby on Rails?this

只是做

@date = Time.now 
@date.strftime("%B %d, %Y") 

而對於後綴ü SE以下

@date.strftime("%B #{@date.day.ordinalize}, %Y") # >>> Gives `June 18th, 2010` 
+0

完美,謝謝你。 – bgadoci 2010-06-15 05:53:37

+0

或者如果您需要其他日期,只需先將其轉換爲日期格式即可。 – paullb 2010-06-15 05:53:43

+0

太棒了。並向我展示了strftime函數和每個無盡的選項。 – gotqn 2013-05-06 20:31:47

0

就在幾天前,有一個類似的問題。在我的回答how do I get name of the month in ruby on Rails?中,我展示瞭如何在config/environment.rb文件中添加自定義to_s定義。

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
:my_own_long_date_format => "%B %d, %Y") 

現在你可以調用Time.now.to_s(:my_own_long_date_format)從任何觀點得到:

June 15, 2010 
2

所需要的時間模塊Time.parse和對的ActiveSupport Integer#ordinalize

require 'time' 
require 'active_support' 

input = '2010-06-14 19:01:00 UTC' 
t = Time.parse(input) 
date = "%s %s, %d" % [t.strftime("%B"), t.day.ordinalize, t.year] 
# => "June 14th, 2010" 
3

你並不需要保存它在一個變量中。

Time.now.strftime("%Y-%m-%d") # 2013-01-08 
4

時間和日期格式的軌道:

日期

====

db:‘%Y-%m-%d’ 2008-08-20 

long_ordinal:‘&proc’  August 20th, 2008 

long:‘%B %e, %Y’ August 20, 2008 

rfc822:‘%e %b %Y’ 20 Aug 2008 

number:‘%Y%m%d’  20080820 

short:‘%e %b’  20 Aug 

日期時間

====

db:‘%Y-%m-%d’ 2008-08-20 16:56:21 

long_ordinal:‘&proc’  August 20th, 2008 16:56 

long:‘%B %e, %Y’ August 20, 2008 16:56 

rfc822:‘%e %b %Y’ Wed, 20 Aug 2008 16:56:21 -0600 

number:‘%Y%m%d’  20080820165621 

short:‘%e %b’  20 Aug 16:56 

時間

====

db:‘%Y-%m-%d %H:%M:%S’   2008-08-20 16:56:21 

long_ordinal:‘&proc’   August 20th, 2008 16:56 

long:‘%B %d, %Y %H:%M’   August 20, 2008 16:56 

rfc822:‘%a, %d %b %Y %H:%M:%S %z’ Wed, 20 Aug 2008 16:56:21 -0600 

short:‘%d %b %H:%M’    20 Aug 16:56 

number:‘%Y%m%d%H%M%S’    20080820165621 

time:‘%H:%M’      16:56 

例如:

<%= news.created_at.strftime("%B %d, %Y %H:%M") %> 

感謝http://onrails.org/2008/08/20/what-are-all-the-rails-date-formats.html

相關問題