I would recommend to use java.time
. You can build a custom formater using DateTimeFormatterBuilder()
by passing a custom map to the appendText()
method.
Example for am/pm for LocalTime
:
LocalTime localTime = LocalTime.now();
Map<Long, String> map = new HashMap<>();
map.put(0L, "a.m");
map.put(1L, "p.m");
DateTimeFormatter aMpM_formatter = new DateTimeFormatterBuilder()
.appendPattern("hh:mm:ss ")
.appendText(ChronoField.AMPM_OF_DAY, map) // without your custom map 0 is mapped to AM and 1 is mapped to PM
.toFormatter();
System.out.println(localTime.format(aMpM_formatter));
Example for LocalDate
with ordinal suffixes:
LocalDate localDate = LocalDate.now();
Map<Long, String> daysWithSuffix = new HashMap<>(); // map values
daysWithSuffix.put(1L, "1st");
daysWithSuffix.put(2L, "2nd");
daysWithSuffix.put(3L, "3rd");
daysWithSuffix.put(21L, "21st");
daysWithSuffix.put(22L, "22nd");
daysWithSuffix.put(23L, "23rd");
daysWithSuffix.put(31L, "31st");
for (long d = 1; d <= 31; d++) {
daysWithSuffix.putIfAbsent(d, d + "th");
}
DateTimeFormatter thFormatter = new DateTimeFormatterBuilder()
.appendPattern("EEE, MMM ")
.appendText(ChronoField.DAY_OF_MONTH, daysWithSuffix) // mapped values from your custom map
.toFormatter();
System.out.println(localDate.format(thFormatter));
System.out.println(LocalDate.of(2019, Month.MARCH, 1).format(thFormatter));
System.out.println(LocalDate.of(2019, Month.MARCH, 23).format(thFormatter));
Example for LocalDateTime
with ordinal suffixes for date and customized am/pm:
DateTimeFormatter both = new DateTimeFormatterBuilder()
.appendPattern("EEE, MMM ")
.appendText(ChronoField.DAY_OF_MONTH, daysWithSuffix)
.appendLiteral(" ")
.appendPattern("hh:mm:ss ")
.appendText(ChronoField.AMPM_OF_DAY, map)
.toFormatter();
System.out.println(LocalDateTime.now().format(both));