Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 419
Mohit Jain Avatar asked Mar 26 '26 15:03

Mohit Jain


1 Answers

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"
like image 128
Casper Avatar answered Mar 29 '26 04:03

Casper



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!