tl;dr
Use objects, not text, to persist a date value to the database.
Convert your obsolete Date
to a modern Instant
. Send to database with JDBC 4.2.
myPreparedStmt.setObject(
… ,
myJavaUtilDate // Avoid the terrible legacy date-time classes. Use only java.time classes.
.toInstant() // Convert from legacy class to modern. Both represent a moment in UTC.
.atZone( // Adjust from UTC to the wall-clock time used by the people of a particular region, a time zone.
ZoneId.of( "Africa/Tunis" )
) // Returns a `ZonedDateTime` object.
.toLocalDate() // Extract only the date, without time-of-day and without time zone. Returns a `LocalDate` object.
) ;
Smart objects, not dumb strings
When working with date-time values, use date-time types, not String
.
As of JDBC 4.2, we can exchange java.time objects with the database. No need to use the terrible old legacy classes such as java.sql.Date
and java.sql.Timestamp
, and java.util.Date
If you have a java.util.Date
object, immediately convert to its modern replacement, java.time.Instant
. To convert, call new methods on the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Both the legacy class and Instant
represent a moment in UTC. To determine a date or a time-of-day for that moment, we must adjust into our desired/expected time zone. For any given moment, the date and time vary around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract the date-only.
LocalDate ld = zdt.toLocalDate() ;
Send to the database.
myPreparedStmt.setObject( … , ld ) ;
Retrieval:
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
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.