DEV Community

matt swanson
matt swanson

Posted on

6 1

Ordinalize: Adding "-st", "-nd", "-rd", "-th" to dates

Ever written a giant case statement to add "-st", "-nd", "-rd", "-th" to display dates like "March 7th" or "September 1st"?

Converting numbers like 1, 2, 7, 19 into "1st", "2nd", "7th", "19th" is called ordinalizing.

ordinalize(number)
Turns a number into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th.

Instead of manually add special cases, check if your language, library, or framework has a helper built-in.

For example, in Rails, you can call the ordinalize method on a number or use the long_ordinal date format.

> 3.ordinalize
=> "3rd"

> Date.today.to_s(:long_ordinal)
=> "September 29th, 2021"
Enter fullscreen mode Exit fullscreen mode

Happy hacking!

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →