问题描述
将 java.util.Date
对象转换为新的JDK 8 / JSR-310 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
?
Date input = new Date();
LocalDate date = ???
推荐答案
简答:
Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
说明:
尽管有它的名字, java.util.Date
表示时间线上的即时,而不是日期。存储在对象内的实际数据是自1970-01-01T00:00Z(1970年GMT / UTC开始的午夜)之前的毫秒数长。
Despite its name, java.util.Date
represents an instant on the time-line, not a "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).
JSR-310中相当于 java.util.Date
的类是 Instant
,因此有一个方便的方法 toInstant()
提供转换:
The equivalent class to java.util.Date
in JSR-310 is Instant
, thus there is a convenient method toInstant()
to provide the conversion:
Date input = new Date();
Instant instant = input.toInstant();
A java.util.Date
instance has没有时区的概念。如果您在 java.util.Date
上调用 toString()
可能看起来很奇怪,因为 toString
是相对于时区。但是,该方法实际上使用Java的默认时区来提供字符串。时区不是 java.util.Date
的实际状态的一部分。
A java.util.Date
instance has no concept of time-zone. This might seem strange if you call toString()
on a java.util.Date
, because the toString
is relative to a time-zone. However that method actually uses Java's default time-zone on the fly to provide the string. The time-zone is not part of the actual state of java.util.Date
.
An Instant
也不包含有关时区的任何信息。因此,要从 Instant
转换为本地日期,需要指定时区。这可能是默认区域 - ZoneId.systemDefault()
- 或者它可能是应用程序控制的时区,例如来自用户首选项的时区。使用 atZone()
方法应用时区:
An Instant
also does not contain any information about the time-zone. Thus, to convert from an Instant
to a local date it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault()
- or it might be a time-zone that your application controls, such as a time-zone from user preferences. Use the atZone()
method to apply the time-zone:
Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
A ZonedDateTime
包含由本地日期和时间,时区和与GMT / UTC的偏移量。因此,可以使用 toLocalDate()
轻松提取日期 - LocalDate
:
A ZonedDateTime
contains state consisting of the local date and time, time-zone and the offset from GMT/UTC. As such the date - LocalDate
- can be easily extracted using toLocalDate()
:
Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate date = zdt.toLocalDate();
这篇关于将java.util.Date转换为java.time.LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!