Reputation: 189
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.
Upvotes: -1
Views: 204
Reputation: 11100
Two ways to do it:
zdt.truncatedTo(ChronoUnit.MILLIS)
.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
private static final var ldtMillisFormatter =
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS");
...
zdt.format(ldtMillisFormatter)
Upvotes: 5
Reputation: 6246
"... 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
Upvotes: 4
Reputation: 2818
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
.
Upvotes: 0