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()
.withOffsetSameLocal(correctedOffset);
System.out.println(correctedDateTime);
Using your sample date-times this prints
2017-12-28T18:30+08:00
If you want the time at UTC:
correctedDateTime = correctedDateTime.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(correctedDateTime);
This prints the datetime you asked for:
2017-12-28T10:30Z
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).