Java 11 ZonedDateTime - Print Format

144 views Asked by At

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.

3

There are 3 answers

0
k314159 On BEST ANSWER

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)
3
Laurent Schoelens On

You can use the java.time.ZonedDateTime.format(DateTimeFormatter) method with a well constructed java.time.format.DateTimeFormatter object.

You can construct the DateTimeFormatter object with the static method ofPattern but seeing your sample output, the java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME should do the job

Another point is : this class is Thread-safe, so you can safely declare a static class field with your DateTimeFormatter with the good output pattern you want. It was not the case with previous date formatter like java.text.SimpleDateFormat.

0
Reilas On

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

You can manually enter the values.
The list of format-specifiers can be found in the JavaDoc, for DateTimeFormatter.

Similarly, an outline of ISO 8601 can be found on Wikipedia.
Wikipedia – ISO_8601.

ZonedDateTime z = ZonedDateTime.now();
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
String s = z.format(f);

Alternately, use the DateTimeFormatterBuilder class.

ZonedDateTime z = ZonedDateTime.now();
DateTimeFormatterBuilder f
    = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_DATE)
        .appendLiteral('T')
        .appendValue(ChronoField.HOUR_OF_DAY, 2)
        .appendLiteral(':')
        .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
        .appendLiteral(':')
        .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
        .appendLiteral('.')
        .appendValue(ChronoField.MILLI_OF_SECOND, 3);
String s = z.format(f.toFormatter());

Output

2023-11-16T13:02:51.753