There are two different explanations for the two parts you are missing:
Why is the seconds part
LocalDateTime.toString()
(implicitly called when you concatenate the date time to a string) leaves out seconds if they (and fraction of second) are zero. To quote the documentation:
The format used will be the shortest that outputs the full value of
the time where the omitted parts are implied to be zero.
and 'Z' is missing in the converted date
The Z
in the original string is an offset (of zero) from UTC. A LocalDateTime
hasn’t got a UTC offset, so when parsing into a LocalDateTime
you are losing this piece of information. To quote the documentation again a LocalDateTime
is:
A date-time without a time-zone in the ISO-8601 calendar system, such
as 2007-12-03T10:15:30.
To preserve the offset, use OffsetDateTime
instead of LocalDateTime
:
String data = "2019-11-15T18:30:00Z";
OffsetDateTime date = OffsetDateTime.parse(data);
System.out.println(data + "\t" + date);
Output:
2019-11-15T18:30:00Z 2019-11-15T18:30Z
It’s still without the seconds. To print them even though they are zero, use a DateTimeFormatter
like the one you were already using, only for formatting:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX");
System.out.println(data + "\t" + date.format(formatter));
2019-11-15T18:30:00Z 2019-11-15T18:30:00Z
Only never hardcode Z
as a literal in your format pattern string. As I said, it’s an offset. If you hardcode it, you will also print Z
when one day you have got an OffsetDateTime
with a different offset, and your output will be downright wrong. Instead use pattern letter X
for offset.
Links