Java UTC String to Paris Time

397 Views Asked by At

From this time :

String date = "2023-01-31T23:00:00.000Z";

Which is in zulu time (UTC). How can I get the LocalDateTime in Paris time ? which can be UTC+1 or UTC+2 depending on the offeset if it's Summer or Winter.

I tried that but it doses not work :

    String date = "2023-01-31T23:00:00.000Z";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
    LocalDateTime datetime = LocalDateTime.parse(date, formatter);
    System.out.println(datetime);
    System.out.println(datetime.atZone(ZoneId.of("Europe/Paris")));

The output :

2023-01-31T23:00
2023-01-31T23:00+01:00[Europe/Paris]
1

There are 1 best solutions below

3
AyoubMK On

Thanks to @Ole V.V. & @g00se

There is the why to cast a String to LocalDateTime with the right Zone :

Solution 1 :

    String date = "2023-01-31T23:00:00.000Z";
    ZonedDateTime zonedDateTime = ZonedDateTime.parse(date);

    ZoneId paris = ZoneId.of("Europe/Paris");

    LocalDateTime localDateTime = zonedDateTime.withZoneSameInstant(paris).toLocalDateTime();
    System.out.println(localDateTime);

Solution 2 :

    String date = "2023-01-31T23:00:00.000Z";

    ZoneId paris = ZoneId.of("Europe/Paris");

    LocalDateTime localDateTime = Instant.parse(date).atZone(paris).toLocalDateTime();
    System.out.println(localDateTime);