How can I sum up two ZoneOffset's?

java datetime java-time timezone-offset zoneddatetime

76 观看


45 作者的声誉

I have two objects of ZoneOffset's parsed from Strings. How can I sum them up and apply to ZonedDateTime?

For example:
original ZonedDateTime is 2017-12-27T18:30:00, first offset is +03, second offset is +05

How can I get the output of 2017-12-28T18:30:00+08:00 or 2017-12-28T10:30:00?

作者: San 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


39502 作者的声誉


I understand your question this way (please check if correct): You’ve got one ZonedDateTime with a usual offset from UTC. I will call it dateTimeWithBaseOffset. And you’ve got another ZonedDateTime with an offset relative to the offset of the former ZonedDateTime. This is really incorrect; the designers of the class decided that the offset is from UTC, but someone used it differently from the intended. I will call the latter dateTimeWithOffsetFromBase.

Best of course if you can fix the code that produced dateTimeWithOffsetFromBase with the unorthodox offset. I am assuming that for now this will not be a solution you can use. So you need to correct the incorrect offset into an offset from UTC.

It’s not bad:

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

    OffsetDateTime correctedDateTime = dateTimeWithOffsetFromBase.toOffsetDateTime()

Using your sample date-times this prints


If you want the time at UTC:

    correctedDateTime = correctedDateTime.withOffsetSameInstant(ZoneOffset.UTC);

This prints the datetime you asked for:


For a date-time with an offset, we don’t need to use ZonedDateTime, OffsetDateTime will do and may communicate better to the reader what we’re up to (ZonedDateTime works too, though).

作者: Ole V.V. 发布者: 28.12.2017 07:11