Ruby and Rails "Date.today" format
26,750
Solution 1
The answer to your question is ActiveSupport
's core extension to Date
class. It overrides the default implementations of inspect
and 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
Solution 2
Rails' strftime
or to_s
methods should do what you need.
For example, using 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"
Solution 3
If you run this:
require 'date'
p Date.today.strftime("%a, %e %b %Y")
You'll get this: "Sat, 26 Sep 2015"
Comments
-
Lalu almost 2 years
In IRB, if I run following commands:
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:=> 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.Can anybody tell, in Rails how
Date.today
orDate.tomorrow
formats the date to display nicely? -
Lalu over 8 yearsHi Brito, my question is when I run Date.today, how rails is displaying => Sat, 26 Sep 2015?
-
Leo Brito over 8 years@Lalu probably because Rails calls
to_s
somewhere when initializing Date. I'll have to research some more to confirm though. -
Lalu over 8 yearsYes Brito, that is what I also think, but I can't figure it out. Please update your answer if you find out. Thanks anyway!
-
Lalu over 8 yearsThanks Alexey, that is what I was exactly looking for!