myPreparedStatement.setObject( // Directly exchange java.time objects with database without the troublesome old java.sql.* classes.
… ,
LocalDate.parse( // Parse string as a `LocalDate` date-only value.
"2018-01-23" // Input string that complies with standard ISO 8601 formatting.
)
)
The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.util.Date
and java.sql.Date
.
For a date-only value, use LocalDate
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
The java.time classes use standard formats when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( input ) ;
You can directly exchange java.time objects with your database using a JDBC driver compliant with JDBC 4.2 or later. You can forget about transforming in and out of java.sql.* classes.
myPreparedStatement.setObject( … , ld ) ;
Retrieval:
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
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.
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.