java.Clock中的混乱,systemDefaultZone()返回UTC时间 [英] Confusion in java.Clock, systemDefaultZone() returning UTC time

查看:154
本文介绍了java.Clock中的混乱,systemDefaultZone()返回UTC时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么以下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)

推荐答案

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:

2017-07-06T12:48:22.890-04:00 [美国/纽约]

2017-07-06T12:48:22.890-04:00[America/New_York]


如果需要,还可以将其转换为LocalDateTime:

clock.instant().atZone(ZoneId.of("America/New_York")).toLocalDateTime()

结果将为LocalDateTime:

2017-07-06T12:49:47.688

2017-07-06T12:49:47.688


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时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆