Search code examples
javadatetime-parsingzoneddatetimelocaldatetime

ZonedDateTime to LocalDateTime


I have a string representing date time with zone and i want to convert the string expression to LocalDateTime.

I have tried parsing it into ZonedDateTime using parse method but failing with an error

 @SerializedName("Expires")
 private String expires = "Sat, 13 Jun 2020 23:14:21 GMT";

 public LocalDateTime getExpiredDateTime() {
     return ZonedDateTime.parse(expires).toLocalDateTime();
 }

Expected result: a LocalDateTime of 2020-06-13T23:14:21.

Observed result:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Sat, 13 Jun 2020 23:14:21 GMT' could not be parsed at index 0


Solution

  • Java provides a formatter for that particular format of input. That format was used in older protocols such as RFC 1123 (now supplanted by ISO 8601 in modern protocols).

    ZonedDateTime
    .parse(
        "Sat, 13 Jun 2020 23:14:21 GMT" ,
        DateTimeFormatter. RFC_1123_DATE_TIME
    )
    .toLocalDateTime()
    

    That input is of a poorly-designed legacy format. I suggest educating the publisher of that data about ISO 8601.