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

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

    I can't be satisfied by the answers calling for a English-only solution based on manual formats. I've been looking for a proper solution for a while now and I finally found it.

    You should be using RuleBasedNumberFormat. It works perfectly and it's respectful of the Locale.

    0 讨论(0)
  • 2020-11-22 03:14

    There is a simpler and sure way of doing this. The function you'll need to use is getDateFromDateString(dateString); It basically removes the st/nd/rd/th off of a date string and simply parses it. You can change your SimpleDateFormat to anything and this will work.

    public static final SimpleDateFormat sdf = new SimpleDateFormat("d");
    public static final Pattern p = Pattern.compile("([0-9]+)(st|nd|rd|th)");
    
    private static Date getDateFromDateString(String dateString) throws ParseException {
         return sdf.parse(deleteOrdinal(dateString));
    }
    
    private static String deleteOrdinal(String dateString) {
        Matcher m = p.matcher(dateString);
        while (m.find()) {
            dateString = dateString.replaceAll(Matcher.quoteReplacement(m.group(0)), m.group(1));
        }
        return dateString;
    

    }

    0 讨论(0)
提交回复
热议问题