I am using Java 17. I am trying to parse different strings as ZonedDateTime but when I try to convert it to an Instant, the output is not as expected. For eg:
String first = "2020-01-08T21:00:00Z[Europe/Berlin]";
ZonedDateTime zone1 = ZonedDateTime.parse(first);
String second = "2020-01-08T20:00:00Z[UTC]";
ZonedDateTime zone2 = ZonedDateTime.parse(second);
System.out.println(zone1.toInstant());
System.out.println(zone2.toInstant());
The output is (this is wrong, both times should be same):
2020-01-08T21:00:00Z
2020-01-08T20:00:00Z
However, when I create a ZonedDateTime object using constructor and ZoneId I get correct output:
ZonedDateTime z1 = ZonedDateTime.of(2020,1,8,21,0,0,0,ZoneId.of("Europe/Berlin"));
System.out.println(z1.toInstant());
ZonedDateTime z2 = ZonedDateTime.of(2020,1,8,20,0,0,0,ZoneId.of("UTC"));
System.out.println(z2.toInstant());
Output:
2020-01-08T20:00:00Z
2020-01-08T20:00:00Z
Can anyone tell me why my parse method is not working as expected?
Note: This issue is NOT related to DST bug for ZonedTimeZone in JDK8:
Zmeaning offset 0 in your case). It was considered a bug and was fixed so that today the offset is respected no matter if it disagrees with the time zone. Seems you can’t make everyone happy.LocalDateTime ldt = LocalDateTime.parse(first, DateTimeFormatter.ISO_ZONED_DATE_TIME);. Parse the time zone usingZoneId zid = DateTimeFormatter.ISO_ZONED_DATE_TIME.parse(first, ZoneId::from);. Obtain yourZonedDateTimewithldt.atZone(zid). In case of your stringfirstwe get2020-01-08T21:00+01:00[Europe/Berlin], which converts to anInstantof2020-01-08T20:00:00Zas requested. Beware of unpredictable results in the time overlap at fall back where summer time ends.