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

后端 未结 20 1244
逝去的感伤
逝去的感伤 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 03:05

    I wrote my self a helper method to get patterns for this.

    public static String getPattern(int month) {
        String first = "MMMM dd";
        String last = ", yyyy";
        String pos = (month == 1 || month == 21 || month == 31) ? "'st'" : (month == 2 || month == 22) ? "'nd'" : (month == 3 || month == 23) ? "'rd'" : "'th'";
        return first + pos + last;
    }
    

    and then we can call it as

    LocalDate localDate = LocalDate.now();//For reference
    int month = localDate.getDayOfMonth();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(getPattern(month));
    String date = localDate.format(formatter);
    System.out.println(date);
    

    the output is

    December 12th, 2018
    

提交回复
热议问题