DateTimeFormatter to serialize LocalDate as ordinal 1st/2nd/3rd of a month

LunaticJape :

I'd like to display LocalDate as:

first day: 1st;
second day: 2nd;
third day: 3rd;
all rest days: Nth.

e.g. 1980-10-1 as 1st Oct 1980

I'm able to serialize it excluding the first 3 days using DateTimeFormatter.ofPattern("dth MMM yyyy"). Since the first 3 days have a different pattern than the rest days, how to construct the formatter to serialize also the first 3 days?

Arnault Le Prévost-Corvellec :

here is what you are searching : https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatterBuilder.html#appendText-java.time.temporal.TemporalField-java.util.Map-

and here is an exemple :

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
Map<Long, String> mapToRoman = new HashMap<>();
mapToRoman.put(1L, "1st");
mapToRoman.put(2L, "2nd");
mapToRoman.put(3L, "3rd");
mapToRoman.put(4L, "4th");
// continue to map all available days in a month
builder.appendText(ChronoField.DAY_OF_MONTH, mapToRoman );
builder.append(DateTimeFormatter.ofPattern(" MM yyyy", Locale.US));
DateTimeFormatter formatter = builder.toFormatter();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102335&siteId=1