Ken Hume Ken Hume - 1 year ago 91
Java Question

How do you format the day of the month to say "11th", "21st" or "23rd" in Java? (ordinal indicator)

I know this will give me the day of the month as a number (


SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");

But how do you format the day of the month to include an ordinal indicator, say
in Java?

Answer Source
import static*;

String getDayOfMonthSuffix(final int n) {
    checkArgument(n >= 1 && n <= 31, "illegal day of month: " + n);
    if (n >= 11 && n <= 13) {
        return "th";
    switch (n % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";

The table from @kaliatech is nice, but since the same information is repeated, it opens the chance for a bug. Such a bug actually exists in the table for 7tn, 17tn, and 27tn (this bug might get fixed as time goes on because of the fluid nature of StackOverflow, so check the version history on the answer to see the error).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download