[英]Ruby and Rails “Date.today” format
In IRB, if I run following commands: 在IRB中,如果我运行以下命令:
require 'date'
Date.today
I get the following output: 我得到以下输出:
=> #<Date: 2015-09-26 ((2457292j,0s,0n),+0s,2299161j)>
But in Rails console, if I run Date.today
, I get this: 但是在Rails控制台中,如果我运行
Date.today
,我会得到这个:
=> Sat, 26 Sep 2015
I looked at Rails' Date class but can't find how Rails' Date.today
displays the output differently than Ruby's output. 我查看了Rails的Date类,但无法找到Rails的
Date.today
如何以不同于Ruby的输出显示输出。
Can anybody tell, in Rails how Date.today
or Date.tomorrow
formats the date to display nicely? 任何人都可以在Rails中告诉
Date.today
或Date.tomorrow
如何格式化日期以便很好地显示?
The answer to your question is ActiveSupport
's core extension to Date
class. 您的问题的答案是
ActiveSupport
对Date
类的核心扩展 。 It overrides the default implementations of inspect
and to_s
: 它会覆盖
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
Command line example: 命令行示例:
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
If you run this: 如果你运行这个:
require 'date'
p Date.today.strftime("%a, %e %b %Y")
You'll get this: "Sat, 26 Sep 2015" 你会得到这个:“星期六,2015年9月26日”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.