How to convert "Tue Feb 27 2024 16:35:30 GMT+0800" String to ZonedDateTime type

36 Views Asked by At

I want to convert "Tue Feb 27 2024 16:35:30 GMT+0800" String to ZonedDateTime type

I use new ZonedDateTime.ofInstant(new Date("Tue Feb 27 2024 16:35:30 GMT+0800").toInstant(), ZoneId.of("Asia/Shanghai"))

but new Date() is Deprecated

1

There are 1 best solutions below

2
Asgar On BEST ANSWER

How about using DateTimeFormatter and trying this?

 public static void main(String[] args) {
        String dateString = "Tue Feb 27 2024 16:35:30 GMT+0800";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateString, formatter);
        ZonedDateTime shanghaiTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
        System.out.println("Parsed ZonedDateTime: " + shanghaiTime);
    }