javadate-formatzoneddatetime

Java 11 ZonedDateTime - Print Format


How could I manage to get the result of 2023-11-16T09:54:12.123 using the ZonedDateTime object in Java 11?

I wrote:

zdt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)

and got ISO_LOCAL_DATE_TIME: 2023-11-16T17:25:27.1881768

I'd like to remove the nanoseconds having only three digits.


Solution

  • Two ways to do it:

    1. Use ISO_LOCAL_DATE_TIME, but truncate the time to milliseconds:
    zdt.truncatedTo(ChronoUnit.MILLIS)
            .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
    
    1. Use a custom formatter and keep the time unchanged:
    private static final var ldtMillisFormatter =
            DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS");
    ...
    zdt.format(ldtMillisFormatter)