Ruby 和 Rails "Date.today" 格式

Ruby and Rails "Date.today" format

在 IRB 中,如果我 运行 以下命令:

require 'date'
Date.today

我得到以下输出:

=> #<Date: 2015-09-26 ((2457292j,0s,0n),+0s,2299161j)> 

但是在 Rails 控制台中,如果我 运行 Date.today,我得到这个:

=> Sat, 26 Sep 2015 

我查看了 Rails' Date class,但无法找到 Rails' Date.today 与 Ruby 的输出不同的显示方式。

谁能告诉我,在 Rails 中,Date.todayDate.tomorrow 如何格式化日期以便更好地显示?

Rails' strftime or 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" 

如果你运行这个:

require 'date'
p Date.today.strftime("%a, %e %b %Y")

你会得到这个:"Sat, 26 Sep 2015"

您问题的答案是 ActiveSupport's core extension to Date class。它覆盖了 inspectto_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

命令行示例:

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