LocalDateTime to java.sql.Date in java 8?

流过昼夜 提交于 2019-11-28 09:11:17

There is no direct correlation between LocalDateTime and java.sql.Date, since former is-a timestamp, and latter is-a Date.

There is, however, a relation between LocalDate and java.sql.Date, and conversion can be done like this:

LocalDate date = //your local date
java.sql.Date sqlDate = java.sql.Date.valueOf(date)

Which for any given LocalDateTime gives you the following code:

LocalDateTime dateTime = // your ldt
java.sql.Date sqlDate = java.sql.Date.valueOf(dateTime.toLocalDate());

@M. Prokhorov's answer is correct, I just want to add a few points.

A java.sql.Date keeps only the day, month and year values. The time values (hour, minute, seconds and milliseconds) are all set to zero. So, when converting a LocalDateTime to a java.sql.Date, these fields are lost.

If you're doing a one-way conversion and don't mind losing those fields, then it's ok to do it:

LocalDateTime dt = // LocalDateTime value
// convert to Date (time information is lost)
java.sql.Date date = java.sql.Date.valueOf(dt.toLocalDate());

But if you want to restore the original LocalDateTime later, it's better to save the time fields separetely, so you can recover it:

LocalDateTime dt = // your LocalDateTime
// save time information (hour, minute, seconds, fraction of seconds)
LocalTime savedTime = dt.toLocalTime();
// convert to Date (time information is lost)
java.sql.Date date = java.sql.Date.valueOf(dt.toLocalDate());

// retrieve back the LocalDate (only day/month/year)
LocalDate localDate = date.toLocalDate();
// retrieve the LocalDateTime, with the original time values
LocalDateTime ldt = localDate.atTime(savedTime);

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());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!