Home > Java > javaTutorial > How Can I Format the Day of the Month with Ordinal Indicators in Java?

How Can I Format the Day of the Month with Ordinal Indicators in Java?

DDD
Release: 2024-12-27 01:09:14
Original
973 people have browsed it

How Can I Format the Day of the Month with Ordinal Indicators in Java?

Formatting Day of Month with Ordinal Indicators

In Java, the SimpleDateFormat class provides a way to format dates and times. While the d format specifier displays the day of the month as a number, there is no built-in way to format the day with an ordinal indicator (e.g., 11th, 21st, 23rd).

Using Guava

The Google Guava library provides a utility class that can be used to generate the ordinal indicator for a given day of the month. The following code snippet demonstrates how to use Guava to format the day of the month with an ordinal indicator:

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

public class DayOfMonthOrdinal {

    public static String getDayOfMonthSuffix(final int n) {
        checkNotNull(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";
        }
    }

    public static void main(String[] args) {
        System.out.println(getDayOfMonthSuffix(11)); // 11th
        System.out.println(getDayOfMonthSuffix(21)); // 21st
        System.out.println(getDayOfMonthSuffix(23)); // 23rd
    }
}
Copy after login

Note: The Guava Preconditions class is used to perform input validation.

The above is the detailed content of How Can I Format the Day of the Month with Ordinal Indicators in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template