ISO 8601 DateTimeFormatter truncates the ms of this format:'YYYY-MM-DDTHH:mm:ss.sssZ'

Viewed 969

An online API is requiring this format:

string

completion formatted as ISO 8601 timestamp - 'YYYY-MM-DDTHH:mm:ss.sssZ'
2018-11-21T22:38:15.000Z

I am trying to get any LocalDate at noon to satisfy the requirement, however, when Java looks at Noon or the start of day, it truncates the subseconds. For example:

DateTimeFormatter.ISO_DATE_TIME
                    .withZone(ZoneOffset.UTC)
                    .format(LocalDate.now().atTime(LocalTime.NOON).atZone(ZoneOffset.UTC))

produces:

2021-03-08T12:00:00Z

The api needs the subseconds. Is there a way for me to force the precision?

I tried building one:

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ") but the Z is missing from the output.

3 Answers

You can make use of your own DateTimeFormatter:

private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");

And then use that to format your date:

ZonedDateTime zdt = LocalDate.now().atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
String formatted = DTF.format(zdt);
System.out.println(formatted); // 2021-03-08T12:00:00.000Z

What about using your own format instead of ISO_DATE_TIME?

Have look to DateTimeFormatterBuilder on how to build your own format with the required precision.

And by the way, the format you use does not truncate "the last 0", is just does not show the milliseconds ...

No worries

LocalDateTime and ZonedDateTime have nanosecond precision always. So the milliseconds are not gone, they are just zero. And are not printed from toString() when they are zero.

Edit: I understand from your comment that the following paragraph does not apply to your situation. I am letting it stand for others to whom it may be useful. You most probably do not need to worry. Your API needs ISO 8601 format. In ISO 8601 the milliseconds (and smaller) are optional when they are zero. Most APIs that accept ISO 8601 (and all that I have met), also accept the string without the milliseconds.

Links

Related questions:

And the central link:

Related