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

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

    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;
    

    }

提交回复
热议问题