我有以下时区"2021-06-06T06:00+01:00Europe/London"
当我在那个时区调用toInstant()时,我得到"2021-06-06T05:00“。时钟往前走,为什么早上5点还回来呢?我想早上7点而不是早上5点。
最小可重现性示例:
ZonedDateTime zoned = ZonedDateTime.of(
2021, 6, 6, 6, 0, 0, 0, ZoneId.of("Europe/London"));
System.out.println(zoned);
System.out.println(zoned.toInstant());预期产出: 2021-06-06T07:00
观察到的产出:
2021-06-06 T06:00+01:00欧洲/伦敦2021-06-06 T05:00:00
发布于 2022-04-01 22:03:38
代码1
ZoneId tzLondon = ZoneId.of("Europe/London");
ZonedDateTime zonedDateTime = ZonedDateTime.of(2021, 6, 6, 6, 0, 0, 0, tzLondon);
Instant instant = zonedDateTime.toInstant();
System.out.println(" zoned: " + zonedDateTime);
System.out.println("instant: " + instant);输出1
zoned: 2021-06-06T06:00+01:00[Europe/London]
instant: 2021-06-06T05:00:00Z分区输出基于欧洲/伦敦时区,该时区在夏令时为格林尼治标准时间+1,这就是为什么它似乎是即时输出后1小时(05:00 +1小时= 06:00)的原因。但这两个输出在时间上代表相同的点,只是以不同的格式。
通常在Java中,您不直接处理DST计算,因为Java是为您做的。当您从上面获取ZonedDateTime并添加几个月时,您可以看到这一点。
代码2
ZonedDateTime zonedDateTimeAFewMonthsLater = zonedDateTime.plusMonths(5);
Instant instantAFewMonthsLater = zonedDateTimeAFewMonthsLater.toInstant();
System.out.println("A few months later (zoned): " + zonedDateTimeAFewMonthsLater);
System.out.println("A few months later (instant): " + instantAFewMonthsLater);输出2
A few months later (zoned): 2021-11-06T06:00Z[Europe/London]
A few months later (instant): 2021-11-06T06:00:00Z但是,如果您真的想从06:00到07:00修补您的ZonedDateTime,这取决于它的DST属性,您可以这样做。但它很脏。
代码3
Duration dstDuration = zonedDateTime.getZone().getRules().getDaylightSavings(instant);
ZonedDateTime dstPatchedZonedDateTime = zonedDateTime.plus(dstDuration);
System.out.println("DST patched: " + dstPatchedZonedDateTime);输出3
DST patched: 2021-06-06T07:00+01:00[Europe/London]发布于 2022-04-01 21:50:43
2021-06-06T06:00+01:00 =
2021-06-06T05:00+00:00
这就是定义时区偏移量的简单方法,例如检查维基百科。
+01:00的时区指示符意味着给定的时间比UTC高出1小时,这意味着在UTC中相同的时间是给定的时间-1小时。
因此,2021-06-06T06:00+01:00和2021-06-06T05:00+00:00是同一时刻,如果没有夏令时间,它将是一天中的1小时。
ZonedDateTime
.parse( "2021-06-06T06:00+01:00[Europe/London]" )
.toInstant()
.toString()2021-06-06 T05:00:00 Z
https://stackoverflow.com/questions/71711182
复制相似问题