Home >Java >javaTutorial >How to Format Dates with Ordinal Indicators (1st, 2nd, 3rd) in Java?

How to Format Dates with Ordinal Indicators (1st, 2nd, 3rd) in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 03:20:25362browse

How to Format Dates with Ordinal Indicators (1st, 2nd, 3rd) in Java?

Formatting Days of the Month with Ordinal Indicators (th, rd)

When displaying the day of the month, it is often desirable to include an ordinal indicator to denote whether it is the "1st", "2nd", "3rd", etc. While Java's SimpleDateFormat provides a way to format the numerical day of the month ("d"), it does not include ordinal indicators.

Ordinal Indicator Formatting

To format the day of the month with an ordinal indicator, you can use a custom function or rely on external libraries. One such library is Google Guava, which offers a method called getDayOfMonthSuffix.

import static com.google.common.base.Preconditions.*;

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";
    }
}

In this example, getDayOfMonthSuffix takes a day of the month as input and returns the corresponding ordinal indicator. It handles special cases where the day ends in "11", "12", or "13" to return "th" instead of "st", "nd", or "rd".

Using this method, you can now format days of the month with ordinal indicators:

SimpleDateFormat sdf = new SimpleDateFormat("MMMMM d");
int dayOfMonth = 21;
String formattedDate = sdf.format(new Date()) + getDayOfMonthSuffix(dayOfMonth);
System.out.println(formattedDate); // prints "January 21st"

Addressing Potential Bugs

Note that it is important to consider corner cases and special situations when formatting days of the month with ordinal indicators. For instance, the table mentioned in the question contains an error for days ending in "7tn", "17tn", and "27tn". To avoid such bugs, it is advisable to use robust custom code or rely on well-tested libraries.

The above is the detailed content of How to Format Dates with Ordinal Indicators (1st, 2nd, 3rd) in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn