简体   繁体   中英

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM