I have a java program which will check for start date and end date of each item. Each Item must have their own specific start date and end date range. And this system will promp
Date ranges can be tricky...
First you want to make sure that the original start date is not equal to the compare start or end date and that the original end date is not equal to the compare start or end date
startDate.equals(originalStartDate) ||
startDate.equals(originalEndDate) ||
endDate.equals(originalStartDate) ||
endDate.equals(originalEndDate)
If that's all okay (false
), you then need to check if the compare start date falls between the original start or end date and if the compare end date falls between the original start or end date...
(startDate.after(originalStartDate) || startDate.before(originalEndDate) ||
(endDate.after(originalStartDate) || endDate.before(originalEndDate)
This tries to capture any point where the two ranges either include or overlap each other...
And because I actual wrote some test code...
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CompareDates {
public static void main(String[] args) {
try {
List events = new ArrayList(3);
events.add(new Event(toDate("01/08/2014"), toDate("01/09/2014")));
events.add(new Event(toDate("02/09/2014"), toDate("30/09/2014")));
Date start = toDate("18/08/2014");
Date end = toDate("30/08/2014");
for (Event evt : events) {
System.out.println(evt.conflicts(start, end));
}
} catch (ParseException exp) {
exp.printStackTrace();
}
}
public static Date toDate(String value) throws ParseException {
return new SimpleDateFormat("dd/MM/yyyy").parse(value);
}
public static class Event {
private Date startDate;
private Date endDate;
public Event(Date startDate, Date endDate) {
this.startDate = startDate;
this.endDate = endDate;
}
public boolean conflicts(Date start, Date end) {
return start.equals(startDate) ||
start.equals(endDate) ||
end.equals(startDate) ||
end.equals(endDate) ||
(start.after(startDate) && start.before(endDate)) ||
(end.after(startDate) && end.before(endDate));
}
}
}