0

I am trying to convert the String which is in the format: 2020-11-23T14:28:45.237Z to LocalDateTime using DateTimeFormatter as below:

String dateTimeInString = "2020-11-23T14:28:45.237Z";

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSZ");
LocalDateTime timestamp = LocalDateTime.parse(dateTimeInString, formatter);

But it's giving an exception. Need a guidance on this. Thanks!

Michael
  • 41,989
  • 11
  • 82
  • 128
ekansh
  • 716
  • 8
  • 16
  • 3
    `LocalDateTime` doesn't have timezone information, use `ZonedDateTime`. – daniu Nov 23 '20 at 14:39
  • 1
    @ekansh `Z` at the end means `UTC` - for support of time zone you have to use a date-time formats like ZonedDateTime or OffsetDateTime. – catch23 Nov 23 '20 at 14:49
  • Your pattern just doesn't match your input string. You're missing the `T` and the `Z` should be an `X` (which handles Z). – Sotirios Delimanolis Nov 23 '20 at 15:25
  • 1
    Please always include your exception message and stack trace. – Sotirios Delimanolis Nov 23 '20 at 15:25
  • Does this answer your question? [Illegal pattern character 'T' when parsing a date string to java.util.Date](https://stackoverflow.com/questions/2597083/illegal-pattern-character-t-when-parsing-a-date-string-to-java-util-date) – Ole V.V. Nov 24 '20 at 14:56

2 Answers2

2

LocalDateTime doesn't have zone part, you need to use ZonedDateTime without DateTimeFormatter only in your case, because your dateTimeInString can be parsed by the default patter of ZonedDateTime:

ZonedDateTime zdt = ZonedDateTime.parse(dateTimeInString);
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

your date time value ("2020-11-23T14:28:45.237Z") have a zone part and you need to use ZoneDateTime to parse zone Date and Time because it because LocaleDateTime doesn't have info about zone:

String dateTimeInString = "2020-11-23T14:28:45.237Z";
ZonedDateTime zdt = ZonedDateTime.parse(dateTimeInString);
System.out.println(zdt.format(DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss"))
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36