tl;dr
myPreparedStatement.setObject(
… ,
LocalDate.parse(
"01/01/1900" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
)
Details
The Answer by Just another Java programmer is correct.
Furthermore, you should not use strings to communicate date-time values with a database. Use date-time classes.
The modern way is with java.time classes, supplanting the troublesome legacy date-time classes.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
You can parse directly from a string in standard ISO 8601 format.
LocalDate localDate = LocalDate.parse( "2016-01-23" );
Or specify each part.
LocalDate localDate = LocalDate.of( 2016, Month.JANUARY , 23 );
To parse other formats, use DateTimeFormatter
class. Search Stack Overflow for many examples.
Database
If your JDBC driver complies with JDBC 4.2 or later, it should be able to pass a java.time type with PreparedStatement::setObject
and fetch with ResultSet::getObject
.
myPreparedStatement.setObject( … , localDate );
…or…
myPreparedStatement.setObject( … , localDate , JDBCType.DATE );
If your driver is not so enabled, fall back to using java.sql.Date
. This awkward class pretends to represent a date-only value (but actually has a time component set to midnight which we are supposed to ignore). To convert to/from java.time look to new methods added to the old classes.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
And going the other direction.
LocalDate localDate = sqlDate.toLocalDate();
Pass to PreparedStatement::setDate
.
myPreparedStatement.setDate( … , sqlDate );
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 java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
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.