2011-02-17 37 views

回答

4

看看strftime,這是Time class的it's implementation的鏈接。

有了它,你應該能夠獲得日期做任何你想要的:-)

>> Time.now.strftime("%A, %B %d, %Y at %l%p") 
=> "Thursday, February 17, 2011 at 5PM" 
+1

推薦鏈接(瞭解所有可能的日期增值經銷商)http://www.foragoodstrftime.com/ – Dogbert 2011-02-17 16:10:17

3

http://api.rubyonrails.org/classes/DateTime.html#method-i-to_formatted_s

如果你想要做的當前日期和時間,只是做:

Time.current.to_formatted_s(:long_ordinal) 

獲得:

February 17th, 2011 12:16 

如果你想編寫你自己的格式,api會顯示你如何在那個鏈接中做到這一點。以下是可用的格式列表:

%a weekday name. 
%A weekday name (full). 
%b month name. 
%B month name (full). 
%c date and time (locale) 
%d day of month [01,31]. 
%H hour [00,23]. 
%I hour [01,12]. 
%j day of year [001,366]. 
%m month [01,12]. 
%M minute [00,59]. 
%p AM or PM 
%S Second [00,61] 
%U week of year (Sunday)[00,53]. 
w weekday [0(Sunday),6]. 
W week of year (Monday)[00,53]. 
x date (locale). 
%X time (locale). 
%y year [00,99]. 
%Y year [2000]. 
%Z timezone name. 

我建議to_formatted_s過的strftime的唯一原因是因爲具有良好的配置/初始化/ time_formats.rb,你可以保持你的看法機。

2

我很驚訝沒有發現「慢性」的寶石,所以我寫了一個。它將在你的ActiveRecord對象上工作。

只要gem在您的created_at字段或任何其他具有ActiveSupport :: TimeWithZone類的字段上安裝並調用'漂亮'方法。

+0

這個已經存在的Rails。查看`initializers/date_time_formats.rb` - 這些指定的格式可以傳遞給`ActiveSupport :: TimeWithZone#to_s`。請參閱[時間#to_formatted_s](http://api.rubyonrails.org/classes/Time.html#method-i-to_formatted_s)。相對的時代,有`time_ago_in_words`助手。 – 2013-07-16 03:25:58

相關問題