Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Compare dates to check if in range

Tags:

java

date

ok not as simple as title may make it sound. I tried this in a very primal way with c# and it worked, but I have a feeling a better job could be achieved with Java and Oracle as database. So the thing is:

I have a reservation system. multiple bookings could be made on the same day for period between date X and date Y as long as each day in the range can accommodate the requested number. Maximum number of clusters to reserve is 46. Hence logically you would look at each day as a holder of 46 cluster reservation and deduce from that.

Now what I have difficulty working out is:

when there are n number of bookings stored and valid in database, then I want to make new booking. So how do I check if this new date range falls within any of the previously booked days or not. Not talking simply here about x falling in y (as ranges). More like:

   X_______________________________________Y
       X________________________________y
  X________________________________Y
                         X________________________________Y

as u can see the overlap is happening.

Please let me know how could I do this as it will affect early design of objects Regards

like image 990
sys_debug Avatar asked Nov 06 '11 21:11

sys_debug


People also ask

How do I check if a date is within a certain range in Java?

The idea is quite simple, just use Calendar class to roll the month back and forward to create a “date range”, and use the Date. before() and Date. after() to check if the Date is within the range.

How do I compare two date ranges in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.


1 Answers

Assume your date has two methods: isBefore(Date other) and isAfter(Date other). Obviously if they don't you can cure this with an external method or wrapping or something. Edit: java.util.Date has compareTo method you could use.

You do this:

public boolean overlapsWithExisting(Booking booking) {
    final Date early = booking.getStart();
    final Date late = booking.getEnd();
    for(Booking existing : existingBookings) {
        if(!(early.isAfter(existing.getEnd()) || late.isBefore(existing.getStart()))
            return true;
    }
    return false;
}

We compare this booking to all existing bookings. If this booking ends before the existing booking even starts, or if this booking starts after the existing booking ends, then it doesn't conflict. Any other condition and they will overlap.

Do this to each booking.

like image 193
corsiKa Avatar answered Sep 24 '22 23:09

corsiKa