Search code examples
javaintervalsdate-comparisondate

Date.after and Data.after in the same if statement


If I have a list of rooms and a specific room called room1 which is booked between 2018-12-12 and 2018-12-20.

And another user wants to book that room between 2018-12-15 and 2018-12-25. I tried to use date.after(checkInDate) and date.after(checkOutDate) but it didn't work. How can it be fixed?

 Date tempStart = checkinDate;
 Date tempEnd = checkoutDate;

 LinkedList<Integer> roomNbrs = new LinkedList<>();

 for (Booking b: books) {

     if (tempStart.equals(b.getCheckinDate()) && tempEnd.equals(b.getCheckoutDate()) && !roomNbrs.contains(roomNbr) ||
                (tempStart.after(b.getCheckinDate())) && ((tempEnd.before(b.getCheckoutDate()) || tempEnd.equals(b.getCheckoutDate()))
                        && !roomNbrs.contains(roomNbr)) ||
                ((tempStart.before(b.getCheckinDate()) || tempStart.equals(b.getCheckinDate()))
                        && tempEnd.before(b.getCheckoutDate()) && !roomNbrs.contains(roomNbr))){

             roomNbrs.add(b.getRoomNbr());
     }
}

Solution

  • I managed to fix the problem and here is the solution:

    private void viewAvailableRoomDate(Date tempStart, Date tempEnd) {
    
        LinkedList<Integer> roomNbrs = new LinkedList<>();
    
        for (Booking b : books) {
    
            if ((!(tempStart.after(b.getCheckinDate()) && tempEnd.after(b.getCheckinDate())) ||
                    (tempStart.before(b.getCheckoutDate()) && tempEnd.after(b.getCheckoutDate())) ||
                    (tempStart.before(b.getCheckinDate()) && tempEnd.after(b.getCheckoutDate()))) ||
                    (tempStart.after(b.getCheckinDate()) && tempEnd.before(b.getCheckoutDate()))){
                roomNbrs.add(b.getRoomNbr());
            }
        }
    

    }