tl;dr
LocalDate.parse( "2018-01-23" )
Details
The Answer by Elliott Frisch is correct. One comment there asked if is there is a better conversion recommended. There is indeed a better way. Bonus: that better way avoids the original problem, confusing java.util.Date
with java.sql.Date
.
java.time
The java.time framework built into Java 8 and later supplants the poorly-designed troublesome old java.util.Date
/.Calendar
classes and their kin. The new classes are inspired by the highly successful Joda-Time framework, similar in concept but re-architected. Defined by JSR 310. See the Oracle Tutorial. Extended by the ThreeTen-Extra project. Back-ported to Java 6 & 7 by the ThreeTen-Backport project, which is wrapped for use in Android by the ThreeTenABP project.
The LocalDate
class represents a date-only value, without time-of-day and without time zone.
ISO 8601
Your input string happens to comply with the ISO 8601 standard.
This standard is used by default in the java.time classes for parsing/generating date-time strings. So no need to specify a formatting pattern.
LocalDate localDate = LocalDate.parse( "2016-01-23" );
Database
As of JDBC 4.2 and later, you can exchange java.time objects directly with your database via getObject
/setObject
methods.
JDBC 4.2 and later
Insert/Update.
myPreparedStatement.setObject( … , localDate ) ;
Retrieval.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
JDBC 4.1 and earlier
If your JDBC driver is not yet updated for JDBC 4.2 or later, convert between java.time and java.sql types. The old java.sql classes have new methods for such conversions.
For LocalDate
, convert to/from the java.sql.Date
class (which pretends to be a date-only value).
java.sql.Date mySqlDate = java.sql.Date.valueOf( localDate );
…and going the other direction…
java.time.LocalDate localDate = mySqlDate.toLocalDate();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.