我如何总结两个ZoneOffset?

问题描述 投票:-2回答:1

我有两个ZoneOffset的对象从字符串解析。我如何总结并适用于ZonedDateTime

例如: 原始ZonedDateTime是2017-12-27T18:30:00,第一个偏移是+03,第二个偏移是+05

如何获得2017-12-28T18:30:00+08:002017-12-28T10:30:00的输出?

java datetime java-time timezone-offset zoneddatetime
1个回答
2
投票

我这样理解你的问题(请检查一下是否正确):你有一个ZonedDateTime与UTC的通常偏差。我会称之为dateTimeWithBaseOffset。你还有另一个ZonedDateTime相对于前ZonedDateTime的偏移量有偏移量。这真的不对;该类的设计者决定偏移量来自UTC,但有人使用它与预期不同。我将称之为后者dateTimeWithOffsetFromBase

当然,如果你可以修复生成dateTimeWithOffsetFromBase与非正统偏移的代码。我假设现在这不是你可以使用的解决方案。因此,您需要将不正确的偏移更正为与UTC的偏移量。

不算太差:

    ZoneOffset baseOffset = dateTimeWithBaseOffset.getOffset();
    ZoneOffset additionalOffset = dateTimeWithOffsetFromBase.getOffset();
    ZoneOffset correctedOffset = ZoneOffset.ofTotalSeconds(baseOffset.getTotalSeconds()
            + additionalOffset.getTotalSeconds());

    OffsetDateTime correctedDateTime = dateTimeWithOffsetFromBase.toOffsetDateTime()
            .withOffsetSameLocal(correctedOffset);
    System.out.println(correctedDateTime);

使用您的样本日期时间打印

2017-12-28T18:30+08:00

如果你想要UTC的时间:

    correctedDateTime = correctedDateTime.withOffsetSameInstant(ZoneOffset.UTC);
    System.out.println(correctedDateTime);

这将打印您要求的日期时间:

2017-12-28T10:30Z

对于带偏移的日期时间,我们不需要使用ZonedDateTimeOffsetDateTime会做,并且可以更好地与读者沟通我们所做的事情(ZonedDateTime也可以工作)。

© www.soinside.com 2019 - 2024. All rights reserved.