在java8中使用正确的偏移量将OffsetDateTime转换为LocalDateTime
当我尝试转换OffsetDateTime到LocalDateTime从java.time,我希望得到的LocalDateTime与本地时区进行更新。所以,如果我有一个OffsetDateTime的2011-12-03T10:00:00Z,我的本地时区为UTC + 2,我预计LocalDateTime是2011-12-03T12:00:00,但我得到代替2011-12-03T10:00:00。我用的方法,把它toLocalDateTime()说OffsetDateTime了。好像只是截断了日期,去掉了偏移部分,没有调整时间。
所以我试图找出一种方法来获取LocalDateTime代表本地日期时间的 a 考虑到区域偏移。按照这个例子,我想得到2011-12-03T12:00:00
回答
LocalDateTime 将为您提供 OffsetDateTime 的挂钟时间。那是 10:00
您需要先转换为您所在时区的 ZonedDatedTime
像这样
OffsetDateTime off = OffsetDateTime.of(2011,12,3,10,00,0,0, ZoneOffset.UTC);
ZonedDateTime zoned = off.atZoneSameInstant(ZoneId.of("Europe/Athens"));
LocalDateTime athensWallTime = zoned.toLocalDateTime();
System.out.println(athensWallTime);
THE END
二维码