I am looking for a method where I can convert a date into more of a human readable format... for example:
12/02/2013 can be converted to "2nd December 2013" 12/03/2013 should be converted to "3rd December 2013" 11/27/2013 can be converted to "27th November 2013"
Is any function in Ruby/Rails readily available to use or I have to write on my own something to handle "st","nd","rd" and "th" besides date numbers ?
You can try this
t = Time.now()
t.strftime("#{t.day.ordinalize} %B %Y")
It will result in
27th November 2013
You should use the strftime function (which is available in several laguages) in order to format times and dates.
In your case, with minimal effort you can achieve some pretty good results:
Time.now.strftime("%e %b %Y") #=> "27 Nov 2013"
For ordinalization, write a custom function or use Rails' ordinalize (as suggested before).
Here's the source:
def ordinalize(number)
if (11..13).include?(number.to_i.abs % 100)
"#{number}th"
else
case number.to_i.abs % 10
when 1; "#{number}st"
when 2; "#{number}nd"
when 3; "#{number}rd"
else "#{number}th"
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With