LocalDateTime to java.sql.Date in java 8?

Viewed 50266

How to convert LocalDateTime to java.sql.Date in ?

My search on internet mostly give me Timestamp related code or LocalDate to java.sql.Date. I'm looking for LocalDateTime to java.sql.Date.

3 Answers

It is possible to convert from LocalDateTime to java.sql.date while retaining the time part without havng to make assumptions about the time-zone by using java.util.Date as an intermediary:

LocalDateTime dateValue = // your LocalDateTime
java.util.Date utilDate;
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern(dateFormat);
SimpleDateFormat sdf1 = new SimpleDateFormat(dateFormat);
try {
    utilDate = sdf1.parse(dateValue.format(dtf1));
} catch (ParseException e) {
    utilDate = null; // handle the exception
}
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Related