Parse, not format
The format
command generates a string, whereas you are trying to do the opposite, parse a String. So you should have called parse
.
Avoid legacy date-time classes
Another problem: You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Avoid Date
, Calendar
, SimpleDateFormat
, and others not in the java.time package.
Date-only, not date-time
Another problem: You are using a date-time class to represent a date-only value.
The LocalDate
class represents a date-only value without time-of-day and without time zone.
ISO 8601
No need to specify a parsing pattern. Your input happens to be in standard ISO 8601 format. The java.time classes use standard formats by default when parsing and generating strings.
LocalDate ld = LocalDate.parse( "2017-01-23" ) ;
Use objects with database, not strings
Another problem: You are using strings to communicate with your database rather than appropriate data types (objects).
Pass the java.time objects to your database directly with a JDBC driver compliant with JDBC 4.2. Call PreparedStatement::setObject
.
String sql = "INSERT INTO tbl_ ( when_ ) VALUES ( ? ) ; " ;
PreparedStatement ps = connection.prepareStatement( sql ) ;
ps.setObject( 1 , ld ) ; // Pass the java.time object directly.
Going the other direction, use ResultSet::getObject
.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;