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 = ???
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 = ???
this format is from
Date#tostring
Short answer
Explanation
Despite its name,
java.util.Date
represents an instant on the time-line, not a "date". The actual data stored within the object is along
count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).The equivalent class to
java.util.Date
in JSR-310 isInstant
, thus there is a convenient methodtoInstant()
to provide the conversion:A
java.util.Date
instance has no concept of time-zone. This might seem strange if you calltoString()
on ajava.util.Date
, because thetoString
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 ofjava.util.Date
.An
Instant
also does not contain any information about the time-zone. Thus, to convert from anInstant
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 theatZone()
method to apply the time-zone: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 usingtoLocalDate()
:Java 9 answer
In Java SE 9, a new method has been added that slightly simplifies this task:
This new alternative is more direct, creating less garbage, and thus should perform better.
I solved this question with solution below
In this case localDate print your date in this format "yyyy-MM-dd"
first, it's easy to convert a Date to an Instant
Then, you can convert the Instant to any date api in jdk 8 using ofInstant() method:
I have had problems with @JodaStephen's implementation on JBoss EAP 6. So, I rewrote the conversion following Oracle's Java Tutorial in http://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html.