-1
String data = "2019-11-15T18:30:00Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
LocalDateTime date = LocalDateTime.parse(data, formatter);
System.out.println(data + "\t" + date);

When I try to print the converted date I'm not getting the date in Desired format.

Output: 2019-11-15T18:30:00Z 2019-11-15T18:30

Why is the seconds part and 'Z' is missing in the converted date

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Vinay P
  • 1
  • 1

1 Answers1

0

There are two different explanations for the two parts you are missing:

  1. 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.

  2. 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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161