LocalDate
A java.sql.Date
represents a date-only value, without time-of-day and without time zone. Unlike the unfortunately-named java.util.Date
which represents both a date and a time-of-day.
The appropriate Joda-Time class would be LocalDate
.
While a LocalDate
stores no time zone, a time zone is crucial in determining ‘today’. Just after midnight in Paris is still ‘yesterday’ in Montréal.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
LocalDate today = LocalDate.now( zone );
LocalDate yesterday = today.minusDays( 1 );
Convert to a java.sql type. The LocalDate::toString
method generates text formatted according to the ISO 8601 standard, YYYY-MM-DD. For a date-only values that happens to be the same as in SQL format expected by the java.sql.Date.valueOf
method.
java.sql.Date sqlDate = java.sql.Date.valueOf( yesterday.toString() );
By the way… if, instead of Joda-Time, you were using the java.time framework built into Java 8 and later, the code would be nearly the same as shown here. The makers of Joda-Time have asked us to migrate to java.time as soon as is convenient.