Search code examples
javadatetimejava-timezoneddatetimedatetimeformatter

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


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.


Solution

  • 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