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

后端 未结 20 966
逝去的感伤
逝去的感伤 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:57

    Here is an approach that updates a DateTimeFormatter pattern with the correct suffix literal if it finds the pattern d'00', e.g. for day of month 1 it would be replaced with d'st'. Once the pattern has been updated it can then just be fed into the DateTimeFormatter to do the rest.

    private static String[] suffixes = {"th", "st", "nd", "rd"};
    
    private static String updatePatternWithDayOfMonthSuffix(TemporalAccessor temporal, String pattern) {
        String newPattern = pattern;
        // Check for pattern `d'00'`.
        if (pattern.matches(".*[d]'00'.*")) {
            int dayOfMonth = temporal.get(ChronoField.DAY_OF_MONTH);
            int relevantDigits = dayOfMonth < 30 ? dayOfMonth % 20 : dayOfMonth % 30;
            String suffix = suffixes[relevantDigits <= 3 ? relevantDigits : 0];
            newPattern = pattern.replaceAll("[d]'00'", "d'" + suffix + "'");
        }
    
        return newPattern;
    }
    

    It does require that the original pattern is updated just prior to every formatting call, e.g.

    public static String format(TemporalAccessor temporal, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(updatePatternWithDayOfMonthSuffix(temporal, pattern));
        return formatter.format(temporal);
    }
    

    So this is useful if the formatting pattern is defined outside of Java code, e.g. a template, where as if you can define the pattern in Java then the answer by @OleV.V. might be more appropriate

提交回复
热议问题