Java 区域的LocalDateTime不’;t显示区域’;一天中的一小时

Java 区域的LocalDateTime不’;t显示区域’;一天中的一小时,java,datetime,java-time,localdate,Java,Datetime,Java Time,Localdate,我在LocalDateTime lastUpdated中有UTC格式的日期和时间。我想显示给定区域的时间和日期,但无论区域如何,我都会得到一天中相同的时间。对于以下代码: System.out.println(lastUpdated); System.out.println(lastUpdated.atZone(ZoneId.of("Europe/Paris"))); System.out.println(lastUpdated.atZone(ZoneId.of("America/Los_Ang

我在
LocalDateTime lastUpdated
中有UTC格式的日期和时间。我想显示给定区域的时间和日期,但无论区域如何,我都会得到一天中相同的时间。对于以下代码:

System.out.println(lastUpdated);
System.out.println(lastUpdated.atZone(ZoneId.of("Europe/Paris")));
System.out.println(lastUpdated.atZone(ZoneId.of("America/Los_Angeles")));
我得到:

2018-05-26T21:33:46
2018-05-26T21:33:46+02:00[Europe/Paris]
2018-05-26T21:33:46-07:00[America/Los_Angeles]
但我想得到的是:

2018-05-26T21:33:46
2018-05-26T**23**:33:46+02:00[Europe/Paris]
2018-05-26T**14**:33:46-07:00[America/Los_Angeles]

区域信息对我来说是可选的。我只需要在适当的时间在区域。有什么方法可以实现吗?

您使用的是
LocalDateTime
,这是一种没有时区的日期和时间指示,就像您在与自己时区的人讨论日期和时间时使用的那样。
atZone
返回当时该日期的
zoneDateTime
,就好像您在该时区谈论它一样

因此,为了获得不同的时间,您需要将
ZoneDateTime
转换为一个
瞬间
,这是一个时间点,为整个行星标识。然后,该
即时
可以再次转换为
ZoneDateTime

LocalDateTime lastUpdated = LocalDateTime.now();
ZonedDateTime zonedDateTime = lastUpdated.atZone(ZoneId.of("Europe/Paris"));
System.out.println(zonedDateTime);
ZonedDateTime other = ZonedDateTime.ofInstant(zonedDateTime.toInstant(), ZoneId.of("America/Los_Angeles"));
System.out.println(other);
输出:

2018-05-27T21:53:53.754+02:00[Europe/Paris]
2018-05-27T12:53:53.754-07:00[America/Los_Angeles]

我的印象是,你把“无时区信息”和“UTC时区…等同起来,因为当我不说什么是时区时,它是UTC…对吗?”

错。如果你不说时区是什么,那么你就没有关于时区的任何具体信息

所以你的2018-05-26T21:33:46不是一个日期和时间,UTC,而是这个日期的日期和时间的概念,而不知道时区的概念存在。这是当你去问某人今天几号和几点时你得到的。不,他们不会认为你还想考虑它在你现在所在的时区。这家伙根本不会认为有时区这样的东西,但他能知道现在是什么日子和时间

因此,要将日期时间UTC转换为其他时区中的日期时间,请执行以下操作:

ZonedDateTime time = lastUpdated.atZone(ZoneId.of("UTC"));
System.out.println(time);
System.out.println(time.withZoneSameInstant​(ZoneId.of("Europe/Paris")));
System.out.println(time.withZoneSameInstant​(ZoneId.of("America/Los_Angeles")));

您是否尝试过使用
ZoneDateTime
?以及您的研究成果?几乎是更好的复制品。没有记住带ZoneSameinstant的
。回答正确。说“UTC LocalDateTime”在术语上是矛盾的。我明白了。谢谢你的详细解释。我误解了这个概念。现在非常清楚:)我甚至可以使用
OffsetDateTime=lastUpdated.atOffset(ZoneOffset.UTC)然后
time.atzonesamainstant​(…)
@OleV.V。这在语义层面上效果更好。但是当我们进入这个领域时,我开始认为一种或另一种方法并不重要。谢谢你的解释:)这对理解这个想法非常有帮助。