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 = ???
You can convert in one line :
If you're using Java 8, @JodaStephen's answer is obviously the best. However, if you're working with the JSR-310 backport, you unfortunately have to do something like this:
we can use
java.sql.Date
as an intermediate casting to convert betweenLocalDate
andutil.Date
to get
util.Date
fromLocalDate
get thesql.date
from theLocalDate
andcast
it toutil.Date
to get
LocalDate
fromutil.Date
castutil.Date
tosql.Date
first, and then calltoLocalDate()
onsql.Date
Better way is:
Advantages of this version:
works regardless the input is an instance of
java.util.Date
or it's subclassjava.sql.Date
(unlike @JodaStephen's way). This is common with JDBC originated data.java.sql.Date.toInstant()
always throws an exception.it's the same for JDK8 and JDK7 with JSR-310 backport
I personally use an utility class (but this is not backport-compatible):
The
asLocalDate()
method here is null-safe, usestoLocalDate()
, if input isjava.sql.Date
(it may be overriden by the JDBC driver to avoid timezone problems or unnecessary calculations), otherwise uses the abovementioned method.What's wrong with this 1 simple line?