java8中,java.util.Date, java.sql.Date, java.time.LocalDate 的转换异常及处理
/**
*PreparedStatement绑定日期参数的时候,如果传入的是 java.util.Date,则会抛出如下异常
* Caused by: java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
*/
ps.setDate(2, (java.sql.Date) startDate);
ps.setDate(2, new java.sql.Date(startDate.getTime()));
/**
*利用如下方式将Date类型转换为 java.time.LocalDate 类型时,如果Date类型为 java.sql.Date,则会抛出如下异常
* Caused by: java.lang.UnsupportedOperationException
* at java.sql.Date.toInstant(Unknown Source) ~[?:1.8.0_172]
*将java.sql.Date 转换成 java.util.Date后,如下方法正常转换
*/
LocalDate localSuspendDate = suspendDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
public Set<String> getSuspendDate(String stockId, Date startDate, Date endDate, String userId) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
Set<String> suspendDates = new HashSet<>();
try {
logger.info(String.format("[SuspendDate][ %s ]开始请求停复盘信息 ...", userId));
connection = dataSource.getConnection();
ps = connection.prepareStatement(
"select x.stock_id, x.suspend_date, x.resumption_date, x.suspend_reason from stock_suspend_info x where stock_id = ? and x.suspend_date >= ? and x.suspend_date <= ? order by suspend_date");
ps.setString(1, stockId);
ps.setDate(2, new java.sql.Date(startDate.getTime()));
ps.setDate(3, new java.sql.Date(endDate.getTime()));
rs = ps.executeQuery();
while (rs.next()) {
Date suspendDate = new java.util.Date(rs.getDate(2).getTime());
Date resumptionDate = new java.util.Date(rs.getDate(3).getTime());
String suspendReason = rs.getString(4);
if (suspendDate == null || resumptionDate == null) {
continue;
}
logger.info(String.format("[SuspendDate][ %s ][ %s ]在区间[ %s ]-[ %s ]内有停复盘信息,停盘原因 [ %s ]...", userId,
stockId, DateUtils.format(suspendDate, "yyyy-MM-dd"),
DateUtils.format(resumptionDate, "yyyy-MM-dd"), suspendReason));
if (suspendDate.before(resumptionDate)) {
LocalDate localSuspendDate = suspendDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate localResumptionDate = resumptionDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
suspendDates.add(localSuspendDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
while (localSuspendDate.isBefore(localResumptionDate)) {
localSuspendDate = localSuspendDate.plusDays(1);
suspendDates.add(localSuspendDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
}
}
} catch (Exception e) {
throw new XException(XErrorCode.DB_EXCEPTION, e);
} finally {
if (rs != null)
try {
rs.close();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
}
return suspendDates;
}