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

后端 未结 20 968
逝去的感伤
逝去的感伤 2020-11-22 02:41

I know this will give me the day of the month as a number (11, 21, 23):

SimpleDateFormat formatDayOfMonth = new Simple         


        
20条回答
  •  梦如初夏
    2020-11-22 02:53

    Using the new java.time package and the newer Java switch statement, the following easily allows an ordinal to be placed on a day of the month. One drawback is that this does not lend itself to canned formats specified in the DateFormatter class.

    Simply create a day of some format but include %s%s to add the day and ordinal later.

    ZonedDateTime ldt = ZonedDateTime.now();
    String format = ldt.format(DateTimeFormatter
            .ofPattern("EEEE, MMMM '%s%s,' yyyy hh:mm:ss a zzz"));
    

    Now pass the day of the week and the just formatted date to a helper method to add the ordinal day.

    
    int day = ldt.getDayOfMonth();
    System.out.println(applyOrdinalDaySuffix(format, day));
    
    

    Prints

    Tuesday, October 6th, 2020 11:38:23 AM EDT
    

    Here is the helper method.

    Using the Java 14 switch expressions makes getting the ordinal very easy.

    public static String applyOrdinalDaySuffix(String format,
            int day) {
        if (day < 1 || day > 31)
            throw new IllegalArgumentException(
                    String.format("Bad day of month (%s)", day));
        String ord = switch (day) {
            case 1, 21, 31 -> "st";
            case 2, 22 -> "nd";
            case 3, 23 -> "rd";
            default -> "th";
        };
        
        return String.format(format, day, ord);
    }
    

提交回复
热议问题