问题描述
我试图理解为什么以下java.time.Clock
返回的是UTC时间而不是本地时区(EST).
I am trying to understand why the following java.time.Clock
is returning UTC time instead of the local time zone (EST).
C:\Users\Felipe>scala
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_65).
Type in expressions for evaluation. Or try :help.
scala> import java.time._
import java.time._
scala> ZoneId.systemDefault()
res0: java.time.ZoneId = America/New_York
scala> val clock = Clock.systemDefaultZone()
clock: java.time.Clock = SystemClock[America/New_York]
scala> clock.instant
res1: java.time.Instant = 2017-07-06T16:20:04.990Z
我执行上述操作的当前时间是12:20pm
(即显示的UTC时间之前4h)
The current time when I ran the above was 12:20pm
(i.e. 4h before the UTC time shown)
推荐答案
Instant.toString()
方法使用DateTimeFormatter.ISO_INSTANT
格式化程序,该格式化程序又解析并格式化UTC中的Instant
.
The Instant.toString()
method uses DateTimeFormatter.ISO_INSTANT
formatter, which in turn parses and formats the Instant
in UTC.
由于2017-07-06T16:20:04.990Z
与纽约的2017-07-06T12:20:04.990
相同,因此您得到的结果是正确的.
As 2017-07-06T16:20:04.990Z
is the same as 2017-07-06T12:20:04.990
in New York, the results you're getting are correct.
如果要将Instant
转换为您的时区,可以执行以下操作:
If you want the Instant
converted to your timezone, you can do:
clock.instant().atZone(ZoneId.systemDefault())
或者您可以更具体一些(因为即使在运行时也可以更改系统的默认时区):
Or you can be more specific (as the system's default timezone can be changed, even in runtime):
clock.instant().atZone(ZoneId.of("America/New_York"))
这将导致ZonedDateTime
:
如果需要,还可以将其转换为LocalDateTime
:
clock.instant().atZone(ZoneId.of("America/New_York")).toLocalDateTime()
结果将为LocalDateTime
:
PS:为 @Andreas在评论中提醒了我(我忘了提及),Instant
类仅表示一个时间点(自1970-01-01T00:00Z
以来的纳秒数),并且没有时区信息,因此任何表示它(包括toString()
方法)将使用UTC.要获取与Instant
相对应的本地日期或时间,必须提供一个时区,如上所示.
PS: as @Andreas reminded me in the comments (and I forgot to mention), the Instant
class represents just a point in time (number of nanoseconds since 1970-01-01T00:00Z
) and has no timezone information, so any representation of it (including the toString()
method) will be in UTC. To get the local date or time that corresponds to an Instant
, you must provide a timezone, as shown above.
这篇关于java.Clock中的混乱,systemDefaultZone()返回UTC时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!