A concise cheat sheet for manipulating Date/Time objects in the most popular Java libraries and converting between Date/Time object types.
java.sql.Date
Converting between other DateTime types
LocalDate
For when we only care about the date and not the time.
public java.time.LocalDate getLocalDate(final java.sql.Date date) {
return date == null ? null : date.toLocalDate();
}
public java.sql.Date getSqlDate(final java.time.LocalDate localDate) {
return localDate == null ? null : java.sql.Date.valueOf(localDate);
}
LocalDateTime
When we need both the date and time values to convert appropriately.
public java.sql.Date getCurrentSqlDate() {
return new java.sql.Date(getCurrentDate().getTime());
}
@Override
public LocalDateTime getLocalDateTimeAtStartOfDay(final java.sql.Date sqlDate) {
return getLocalDate(sqlDate).atStartOfDay();
}
@Override
public LocalDateTime getLocalDateTimeAtEndOfDay(final java.sql.Date sqlDate) {
return getLocalDate(sqlDate).atTime(23, 59, 59, 59);
}
@Override
public java.sql.Date getCurrentSqlDateMidnight() {
// simple and not unduly inefficient way to truncate the time component
return java.sql.Date.valueOf(getCurrentSqlDate().toString());
}
@Override
public java.sql.Date convertToSqlDate(final String dateString) throws ParseException {
if (StringUtils.isBlank(dateString)) {
throw new IllegalArgumentException("invalid (blank) dateString");
}
final Date date = parseAgainstFormatArray(dateString, stringToDateFormats);
return new java.sql.Date(date.getTime());
}
@Override
public java.sql.Date convertToSqlDate(final Timestamp timestamp) {
return new java.sql.Date(timestamp.getTime());
}