我必须检查预订的开始日期和结束日期是否在用户选择的时间跨度之间。因此,如果用户说他想要查看从2月12日到2月15日的所有预订,它应该只显示在此时间跨度内的预订。我就是想不通,希望有人能帮上忙。到目前为止,这是我的尝试:
Timestamp tsBeginning = new Timestamp(dateBeginning.getTime()); //date entered by user
Timestamp tsEnd = new Timestamp(dateEnd.getTime()); //date entered by user
for (Booking b : bookingList) {
if(((b.getBeginning().after(tsBeginning) || b.getBeginning().equals(tsBeginning)) && b.getBeginning().before(tsEnd) || b.getBeginning().equals(tsEnd))
&& ((b.getEnd().after(tsEnd) || b.getEnd().equals(tsEnd)) && (b.getEnd().before(tsEnd) || b.getEnd().equals(tsEnd)))){
bookingsForRoomInPeriod.add(b);
发布于 2018-06-11 03:52:55
编辑:它花了很长时间的讨论。我似乎终于明白了:预订是在一天中的某个日期和一个小时开始和结束的(比如6月14日下午3:30 )。用户输入开始日期和结束日期,但不输入小时。您需要包括完全包含在日期范围内的预订。也就是说,在开始日期的00:00和结束日期的24:00之间。
LocalDate userBeginning = // …
LocalDate userEnd = // …
LocalDateTime userBeginningTime = userBeginning.atStartOfDay();
LocalDateTime userEndTime = userEnd.plusDays(1).atStartOfDay();
if (! b.getBeginning().isBefore(userBeginningTime)
&& ! b.getEnd().isAfter(userEndTime)) {
bookingsForRoomInPeriod.add(b);
}
我假设getBeginning
和getEnd
返回LocalDateTime
。在Java中,“the end of the day”(午夜)表示为第二天的00:00,这就是为什么我在用户输入的结束日期的基础上加上1天。
您似乎正在使用的Timestamp
类很久以前就过时了。java.time
是现代Java date and time API,使用起来比老式的date和time类好得多。尤其是java.sql
中的date和time类,其丑陋的设计半途而废地试图掩盖它们是(设计也很糟糕的) java.util.Date
的子类。
假设您选择了Timestamp
,因为您从数据库获取时间,并且假设您至少可以使用Java8和JDBC4.2,那么可以使用ResultSet.getObject
方法之一直接从结果集中获取LocalDateTime
对象,并将LocalDateTime.class
作为您想要的类型进行传递。
上一版本的答案:
…只有日期与时间无关,并且只应包括完全在用户所选时间戳内的预订
if (! b.getBeginning().before(tsBeginning) && ! b.getEnd().after(tsEnd)) {
bookingsForRoomInPeriod.add(b);
}
我使用“不在此之前”作为要求“on or after”的简写方式。同样,我用“not after”来表达“之前或之后”。
也就是说,您似乎正在使用的Timestamp
类很久以前就已经过时了,而且也不适合没有时间的日期。使用不带时间的数据库数据类型(在大多数关系数据库中简称为date
),在Java语言中使用java.time
中的LocalDate
。java.time
是现代Java date and time API,使用起来比老式的date和time类好得多。尤其是java.sql
中的date和time类,其丑陋的设计半途而废地试图掩盖它们是(设计也很糟糕的) java.util.Date
的子类。
https://stackoverflow.com/questions/50787433
复制相似问题