本文翻译自:Convert java.util.Date to java.time.LocalDate
What is the best way to convert a java.util.Date
object to the new JDK 8/JSR-310 java.time.LocalDate
? 将java.util.Date
对象转换为新的JDK 8 / JSR-310 java.time.LocalDate
的最佳方法是什么?
Date input = new Date();
LocalDate date = ???
#1楼
参考:https://stackoom.com/question/1R82g/将java-util-Date转换为java-time-LocalDate
#2楼
Short answer 简短答案
Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Explanation 说明
Despite its name, java.util.Date
represents an instant on the time-line, not a "date". 尽管其名称, java.util.Date
表示时间轴上的一个瞬间,而不是“日期”。 The actual data stored within the object is a long
count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC). 自1970-01-01T00:00Z(1970 GMT / UTC开始的午夜)以来,存储在对象中的实际数据是很long
的毫秒数。
The equivalent class to java.util.Date
in JSR-310 is Instant
, thus there is a convenient method toInstant()
to provide the conversion: JSR-310中与java.util.Date
等效的类是Instant
,因此有一个方便的方法toInstant()
提供转换:
Date input = new Date();
Instant instant = input.toInstant();
A java.util.Date
instance has no concept of time-zone. 一个java.util.Date
实例没有时区的概念。 This might seem strange if you call toString()
on a java.util.Date
, because the toString
is relative to a time-zone. 如果在java.util.Date
上调用toString()
,这似乎很奇怪,因为toString
是相对于时区的。 However that method actually uses Java's default time-zone on the fly