【发布时间】:2021-12-25 07:00:30
【问题描述】:
我正在将约会保存到数据库中,并且有一个方法可以检查时间是否重叠。
public static boolean checkForOverlappingAppointment(Timestamp start, Timestamp end, int
customerID) {
try {
String sql = "SELECT * FROM appointments WHERE Customer_ID = ?";
PreparedStatement ps = JDBC.getConnection().prepareStatement(sql);
ps.setString(1, String.valueOf(customerID));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Timestamp startOtherAppts = rs.getTimestamp("Start");
Timestamp endOtherAppts = rs.getTimestamp("End");
if ((start.before(startOtherAppts) && end.after(endOtherAppts)) ||
(start.before(startOtherAppts) && end.after(startOtherAppts) &&
end.before(endOtherAppts)) || (start.after(startOtherAppts) &&
start.before(endOtherAppts) && end.after(endOtherAppts)) ||
(start.after(startOtherAppts) && end.before(endOtherAppts)))
{
return true;
}
}
}
catch (SQLException e) {
e.printStackTrace(); }
return false;
}
我正在调用该方法
if (DBAppointments.checkForOverlappingAppointment(Timestamp.valueOf(startDateTimeZDT.toLocalDateTime()), Timestamp.valueOf(endDateTimeZDT.toLocalDateTime()), customerIDint)) {
Alert alert3 = new Alert(Alert.AlertType.ERROR);
alert3.setHeaderText("APPOINTMENT OVERLAP");
alert3.setContentText("Appointment overlaps with an existing appointment.");
alert3.showAndWait();}
我在保存约会时没有收到任何错误,尽管它们可以是相同的确切时间。
我正在使用Timestamp.valueOf(startDateTimeZDT.toLocalDateTime() Timestamp.valueOf(endDateTimeZDT.toLocalDateTime() 将LocalTime 转换为ZonedDateTime 以保存在数据库中
我似乎无法找出哪里出了问题。任何帮助都会很棒!
【问题讨论】:
-
您正在使用糟糕的日期时间类,这些类在几年前被 JSR 310 中定义的现代 java.time 类所取代。根本不需要使用
Timestamp类. -
这有用吗? Determine Whether Two Date Ranges Overlap。我也建议你不要使用
Timestamp。它的设计很糟糕,是对已经设计很糟糕的“日期”类的真正破解,而且已经过时了。 -
@BasilBourque 我不知道它们已经过时了,哈哈。我只是一个试图遵循规则的学生。当我试图弄清楚这个项目时,我已经转移到 ZonedDateTime 和 LocalDateTimes 。下面的信息帮助我朝着正确的方向前进。
-
为什么它们已经过时了? Official answer here.