In Ruby on Rails, How to Format a Date With the "Th" Suffix, as In, "Sun Oct 5Th"

In Ruby on Rails, how do I format a date with the th suffix, as in, Sun Oct 5th?

Use the ordinalize method from 'active_support'.

>> time = Time.new
=> Fri Oct 03 01:24:48 +0100 2008
>> time.strftime("%a %b #{time.day.ordinalize}")
=> "Fri Oct 3rd"

Note, if you are using IRB with Ruby 2.0, you must first run:

require 'active_support/core_ext/integer/inflections'

How do I format a date with the “th” suffix, on en.yml?

You can pass the string to the locale

en:
foo: "it is the %{day} of %{month} today"

I18n.t('foo', day: Date.today.day.ordinalize, month: Date::MONTHNAMES[Date.today.month] )

In Ruby on Rails, how do I format a date with the th suffix, as in, Sun Oct 5th?

Use the ordinalize method from 'active_support'.

>> time = Time.new
=> Fri Oct 03 01:24:48 +0100 2008
>> time.strftime("%a %b #{time.day.ordinalize}")
=> "Fri Oct 3rd"

Note, if you are using IRB with Ruby 2.0, you must first run:

require 'active_support/core_ext/integer/inflections'

converting a date in ruby to a customised format

You can try this

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

It will result in

27th November 2013

Ruby date time parse to get 'th'

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)

How to get the 'th' and 'rd' on a date?

Your answer is here
That's from an older SO post.

how to convert this (month/day/year ) date format to actual timestamp in rails

I think you just need format that string to valid format to convert to date, something like this:

old_format = '6/21/2021'.split('/')
old_format[0], old_format[1] = old_format[1], old_format[0]
old_format.join('/').to_date

Need to custom format a ruby date object?

d = Date.parse('14 September 2016')

to get your date object.

d.strftime('%b%d.%Y') #=> Sep14.2016

This will format your date like you wanted. Keep in mind d is not modified, so it is still a Date object. You need to assign the result of the strftime method to any variable.

You can use the downcase method to remove any capitalization.



Related Topics



Leave a reply



Submit