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

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

    RuleBasedNumberFormat in ICU library

    I appreciated the link to the ICU project's library from @Pierre-Olivier Dybman (http://www.icu-project.org/apiref/icu4j/com/ibm/icu/text/RuleBasedNumberFormat.html), however still had to figure out how to use it, so an example of the RuleBasedNumberFormat usage is below.

    It will only format single number rather than the whole date, so you will need to build a combined string if looking for a date in format: Monday 3rd February, for example.

    The below code sets up the RuleBasedNumberFormat as an Ordinal format for a given Locale, creates a java.time ZonedDateTime, and then formats the number with its ordinal into a string.

    RuleBasedNumberFormat numOrdinalFormat = new RuleBasedNumberFormat(Locale.UK,
        RuleBasedNumberFormat.ORDINAL);
    ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Pacific/Auckland"));
    
    String dayNumAndOrdinal = numOrdinalFormat.format(zdt.toLocalDate().getDayOfMonth());
    

    Example output:

    3rd

    Or

    4th

    etc.

提交回复
热议问题