JSR 310 :: System.currentTimeMillis()与Instant.toEpochMilli():: TimeZone
问题内容:
您能否说明一下如何为默认系统时区和给定时区获取正确的纪元时间(以毫秒为单位)。
给定
1.时区:GMT + 3
2.以下代码段:
import java.time.*;
public class Main {
public static void main(String[] args) {
System.out.println(LocalDateTime
.now()
.atZone(ZoneOffset.UTC)
.toInstant()
.toEpochMilli()
);
System.out.println(LocalDateTime
.now()
.atZone(ZoneOffset.of("+3"))
.toInstant()
.toEpochMilli()
);
System.out.println(System.currentTimeMillis());
}
}
3.输出:
1444158955508
1444148155508
1444148155508
4.
System.currentTimeMillis()的
JavaDoc,它指示返回值将是 当前时间与UTC 1970年1月1日午夜之间的差(以毫秒为单位)。
所以为什么
LocalDateTime
at 的输出与of的输出GMT+3
相同System.currentTimeMillis()
,尽管System.currentTimeMillis()
提及的文档UTC
?LocalDateTime
at 的输出UTC
与有所不同System.currentTimeMillis()
,尽管System.currentTimeMillis()
提及的文档UTC
?
问题答案:
双方System.currentTimeMillis()
并Instant.toEpochMilli()
自Unix纪元返回的毫秒数。尽管Unix时期通常表示为“
UTC 1970年1月1日午夜”,但这并不是“在任何特定时区中”。但是瞬间只是时间的瞬间,无论您处于哪个时区都是相同的-但它将反映不同的本地时间。
的输出LocalDateTime.atZone(UTC)
有所不同,因为您说的是“获取本地日期和时间,并将其转换 为与UTC时区相同的时刻
”-即使您创建时是LocalDateTime
在UTC + 3时间中隐式执行的区域…这就是为什么它是“错误的”。
LocalDateTime.now()
采用 系统默认时区中 的本地日期和时间。因此,如果您的时区为UTC +
3,则当前时间为2015-10-06T16:57:00Z,LocalDateTime.now()
则将返回.2015-10-06T19:57:00
。让我们称之为localNow
…
因此,localNow.atZone(ZoneOffset.of("+3"))
将返回ZonedDateTime
代表2015-10-06T19:57:00
+ 03-换句话说,相同的本地日期/时间,但“知道”它比UTC早3小时…因此toInstant()
将返回Instant
代表2015-10
-06T16:57:00Z。很好-我们仍然有当前日期/时间。
但是localNow.atZone(ZoneOffset.UTC)
将返回ZonedDateTime
代表2015-10-06T19:57:00Z-换句话说,相同的本地日期/时间,但“认为”它已经存在于UTC中,因此toInstant()
将返回Instant
代表2015-10-06T19:57
:00Z ..根本不是当前时间(三个小时之内)。