18. Customizing localized date-time formats
Starting with JDK 8, we have a comprehensive date-time API containing classes such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime, and OffsetTime.
We can easily format the date-time output returned by these classes via DateTimeFormatter.ofPattern(). For instance, here, we format a LocalDateTime via the y-MM-dd HH:mm:ss pattern:
// 2023-01-07 15:31:22 String ldt = LocalDateTime.now() .format(DateTimeFormatter.ofPattern("y-MM-dd HH:mm:ss")); More examples are available in the bundled code.
How about customizing our format based on a given locale – for instance, Germany?
Locale.setDefault(Locale.GERMANY); We accomplish this via ofLocalizedDate(),ofLocalizedTime(), and ofLocalizedDateTime(), as in the following examples:
// 7. Januar 2023 String ld = LocalDate.now().format( DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)); // 15:49 String lt = LocalTime.now().format...