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 } }
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!