Ruby date time parse to get 'th'

Viewed 58

I've got date as string '2020-02-10 8,00' which I want to convert into Monday, 10th of February. I'm aware of this old topic however I cannot find (or use) any related information.

All I have is just parsed string to date - Date.parse '2020-02-10 8,00'

1 Answers

You are halfway there! Date.parse '2020-02-10 8,00' produces a ruby Date object, as you have noted. You now have to apply strftime. However strftime doesn't have any ordinalization so that piece has to be done manually.

date = Date.parse('2020-02-10 8,00')

date.strftime("%A, #{date.day.ordinalize} of %B") #=> Monday, 10th of February

the ordinalize method is provided by ActiveSupport.

If this format will be used multiple times in your app, you may wish to add an app-wide format:

# in config/initializers/time_formats.rb
Date::DATE_FORMATS(:ordinalized_day) = lambda{|date| date.strftime("%A, #{date.day.ordinalize} of %B")}


# anywhere in the app
Date.today.to_formatted_s(:ordinalized_day)
Related