我如何总结两个 ZoneOffset 的?
How can I sum up two ZoneOffset's?
我有两个对象 ZoneOffset's parsed from Strings. How can I sum them up and apply to ZonedDateTime?
例如:
原始 ZonedDateTime 为 2017-12-27T18:30:00
,第一个偏移量为 +03
,第二个偏移量为 +05
如何获得 2017-12-28T18:30:00+08:00
或 2017-12-28T10:30:00
的输出?
我这样理解你的问题(请检查是否正确):你有一个 ZonedDateTime
与 UTC 的通常偏移量。我将其命名为dateTimeWithBaseOffset
。你还有另一个 ZonedDateTime
,其偏移量相对于前一个 ZonedDateTime
的偏移量。这确实是不正确的; class 的设计者决定偏移量来自 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
对于带有偏移量的日期时间,我们不需要使用 ZonedDateTime
,OffsetDateTime
可以,并且可以更好地与 reader 沟通至(不过,ZonedDateTime
也有效)。
我有两个对象 ZoneOffset's parsed from Strings. How can I sum them up and apply to ZonedDateTime?
例如:
原始 ZonedDateTime 为 2017-12-27T18:30:00
,第一个偏移量为 +03
,第二个偏移量为 +05
如何获得 2017-12-28T18:30:00+08:00
或 2017-12-28T10:30:00
的输出?
我这样理解你的问题(请检查是否正确):你有一个 ZonedDateTime
与 UTC 的通常偏移量。我将其命名为dateTimeWithBaseOffset
。你还有另一个 ZonedDateTime
,其偏移量相对于前一个 ZonedDateTime
的偏移量。这确实是不正确的; class 的设计者决定偏移量来自 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
对于带有偏移量的日期时间,我们不需要使用 ZonedDateTime
,OffsetDateTime
可以,并且可以更好地与 reader 沟通至(不过,ZonedDateTime
也有效)。