Lal*_*alu 4 ruby ruby-on-rails date activesupport
在IRB中,如果我运行以下命令:
require 'date'
Date.today
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
=> #<Date: 2015-09-26 ((2457292j,0s,0n),+0s,2299161j)>
Run Code Online (Sandbox Code Playgroud)
但是在Rails控制台中,如果我运行Date.today
,我得到这个:
=> Sat, 26 Sep 2015
Run Code Online (Sandbox Code Playgroud)
我查看了Rails的Date类,但无法找到Rails如何Date.today
以不同于Ruby的输出显示输出.
任何人都可以告诉Rails如何Date.today
或Date.tomorrow
格式化日期以便很好地显示?
Ale*_*ein 11
你问题的答案是课堂ActiveSupport
的核心延伸Date
.它覆盖的默认实现inspect
和to_s
:
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
def readable_inspect
strftime('%a, %d %b %Y')
end
alias_method :default_inspect, :inspect
alias_method :inspect, :readable_inspect
Run Code Online (Sandbox Code Playgroud)
命令行示例:
ruby-2.2.0 › irb
>> require 'date'
=> true
>> Date.today
=> #<Date: 2015-09-27 ((2457293j,0s,0n),+0s,2299161j)>
>> require 'active_support/core_ext/date'
=> true
>> Date.today
=> Sun, 27 Sep 2015
Run Code Online (Sandbox Code Playgroud)
Rails' strftime
或to_s
方法应该做你需要的.
例如,使用to_s
:
2.2.1 :004 > Date.today.to_s(:long)
=> "September 26, 2015"
2.2.1 :005 > Date.today.to_s(:short)
=> "26 Sep"
Run Code Online (Sandbox Code Playgroud)
小智 5
如果你运行这个:
require 'date'
p Date.today.strftime("%a, %e %b %Y")
Run Code Online (Sandbox Code Playgroud)
您会收到:“2015 年 9 月 26 日星期六”