Java 8 UTC 和祖鲁时间的相等性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28263244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 equality of UTC and Zulu time?
提问by Dag
As far I could research, UTC and Zulu are the same. However I'm running in difficulties comparing two ZonedDateTimes I receive from different sources in my code. The following code illustrates the problem:
据我研究,UTC 和祖鲁语是一样的。但是,我在比较我的代码中从不同来源收到的两个 ZonedDateTime 时遇到了困难。下面的代码说明了这个问题:
@Test
public void equalsOnTimezone() throws Exception {
ZonedDateTime zdtUtc = ZonedDateTime.of(2015, 2, 1, 14, 30, 0, 0, ZoneId.of("UTC"));
ZonedDateTime zdtZ = ZonedDateTime.of(2015, 2, 1, 14, 30, 0, 0, ZoneId.of("Z"));
assertEquals(zdtUtc, zdtZ); // will fail
}
The problem:
问题:
java.lang.AssertionError: expected:<2015-02-01T14:30Z[UTC]> but was:<2015-02-01T14:30Z>
And what will be the correct way to create and compare UTC based values then?
那么创建和比较基于 UTC 的值的正确方法是什么?
According to W3C Date and Time Formats:
根据 W3C日期和时间格式:
Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z").
时间以 UTC(协调世界时)表示,并带有一个特殊的 UTC 指示符(“Z”)。
回答by Stephen C
Comparing zone IDs rather than offsets
比较区域 ID 而不是偏移量
According to the source code, ZonedDateTime::equals
uses ZoneId::equals
to compare the zone id component, and that in turn compares the ids rather than the offsets.
根据源代码,ZonedDateTime::equals
用于ZoneId::equals
比较区域 id 组件,然后比较 ids 而不是偏移量。
If you want two ZonedDateTime
with "different but equivalent" zone ids to compare as equal, you should create them like this, calling ZoneId::normalized
.
如果您希望两个ZonedDateTime
具有“不同但等效”的区域 ID 比较相等,则应该像这样创建它们,调用ZoneId::normalized
.
ZonedDateTime zdtUtc = ZonedDateTime.of(
2015, 2, 1, 14, 30, 0, 0, ZoneId.of("UTC").normalized());
ZonedDateTime zdtZ = ZonedDateTime.of(
2015, 2, 1, 14, 30, 0, 0, ZoneId.of("Z").normalized());
I think this is a case where your expectations (based on the W3C documentation for the string representations) don't correspond to the documented semantics of the Java classes. In such cases, the Javadoc is definitive.
我认为在这种情况下,您的期望(基于 W3C 字符串表示的文档)与 Java 类的文档语义不对应。在这种情况下,Javadoc 是权威的。
(This is nota Java 8 bug, IMO.)
(这不是Java 8 错误,IMO。)