Home >Java >javaTutorial >How Can I Add Ordinal Indicators (st, nd, rd, th) to Day-of-Month Formatting in Java?

How Can I Add Ordinal Indicators (st, nd, rd, th) to Day-of-Month Formatting in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-17 07:43:25592browse

How Can I Add Ordinal Indicators (st, nd, rd, th) to Day-of-Month Formatting in Java?

Formatting Day of the Month with Ordinal Indicator

While SimpleDateFormat allows you to format the day of the month as a number (dd), it does not provide a way to include an ordinal indicator (e.g., 11th, 21st, 23rd).

To achieve this, you can use a combination of logic and string manipulation. Here's an example:

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

This function returns the appropriate ordinal indicator based on the given day of the month. For example, getDayOfMonthSuffix(11) would return "th".

Avoid Table-Based Solutions

While it may seem convenient to use a table to map days to their ordinal indicators, this approach introduces a risk of bugs. For example, if the table is missing or contains errors, it can lead to incorrect results. The code approach outlined above eliminates this potential issue by using logic to calculate the suffix dynamically.

The above is the detailed content of How Can I Add Ordinal Indicators (st, nd, rd, th) to Day-of-Month Formatting 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