Search code examples
ruby-on-railsrubydateformattingstrftime

How to convert date format in Ruby


Here are some outputs:

Date.today  => Mon, 25 Jun 2012 
Date.today.to_formatted_s(:long_ordinal)  => "June 25th, 2012" 
Date.today.strftime('%A %d, %B')  =>  "Monday 25, June" 

Now I need output in the format ie:

  Monday 25th, June      or       Thrusday, 1st, October

Problem is to_formatted_s and strftime apply only on date and both or them return string. How can I get the output in the way I need?


Solution

  • You can use Date::DATE_FORMATS to add a new customized format, and Integer.ordinalize to get the day ordinal:

    Date::DATE_FORMATS[:month_ordinal] = lambda { |date| 
      date.strftime("%A #{date.day.ordinalize}, %B") 
    }
    
    >> Date.today.to_formatted_s(:month_ordinal)
    => "Monday 25th, June"