Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a date in ruby to a customised format [duplicate]

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 ?

like image 265
Kush Avatar asked Feb 14 '26 23:02

Kush


2 Answers

You can try this

t = Time.now()
t.strftime("#{t.day.ordinalize} %B %Y")

It will result in

27th November 2013
like image 96
Jeet Avatar answered Feb 17 '26 16:02

Jeet


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
like image 31
whatyouhide Avatar answered Feb 17 '26 15:02

whatyouhide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!