netdevnet
netdevnet

Reputation: 49

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

Upvotes: 0

Views: 3398

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338496

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.

Upvotes: 4

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateTimeStr = "Sat, 13 Jun 2020 23:14:21 GMT";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss z");
        ZonedDateTime zdt = ZonedDateTime.parse(dateTimeStr, formatter);
        System.out.println(zdt);

        LocalDateTime ldt = zdt.toLocalDateTime();
        System.out.println(ldt);
    }
}

Output:

2020-06-13T23:14:21Z[GMT]
2020-06-13T23:14:21

[Update] Courtesy Basil Bourque

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateTimeStr = "Sat, 13 Jun 2020 23:14:21 GMT";

        DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;

        ZonedDateTime zdt = ZonedDateTime.parse(dateTimeStr, formatter);
        System.out.println(zdt);

        LocalDateTime ldt = zdt.toLocalDateTime();
        System.out.println(ldt);
    }
}

Output:

2020-06-13T23:14:21Z
2020-06-13T23:14:21

Upvotes: 2

Related Questions