-1

i have two dates with me startDate and endDate

from method parameters i am getting newStartDate and newEndDate

And now i need to check newStartDate and newEndDate are not in between or even conflicting with startDate and endDate

for example:

start date = 11/03/2016
end date = 11/15/2016


newStartDate = 11/16/2016
newEndDate = 11/23/2016
(^^^This one should return true)

newStartDate = 11/01/2016
newEndDate = 11/02/2016
(^^^This one should return true)

newStartDate = 11/04/2016
newEndDate = 11/12/2016
(^^^This one should return false)

newStartDate = 11/01/2016
newEndDate = 11/05/2016
(^^^This one should return false)

newStartDate = 11/12/2016
newEndDate = 11/22/2016
(^^^This one should return false)  

newStartDate = 11/01/2016
newEndDate = 11/24/2016
(^^^This one should return false)

newStartDate = 11/01/2016
newEndDate = 11/03/2016
(^^^This one should return false) 

please help me to write java code for this kind of logic.

user3521432
  • 2,230
  • 3
  • 13
  • 16

1 Answers1

2

The easiest way to compare dates is to convert them to Date object first. This can be done as follows:

DateFormat dateFormat = new SimpleDateFormat("DD/MM/YYYY");
Date startDate = dateFormat.parse("11/03/2016");
Date endDate = dateFormat.parse("11/23/2016");

Once you have all your dates in Date variables then your check for overlap is pretty trivial:

boolean overlap = newStar.compareTo(endDate) <= 0 && newEnd.compareTo(startDate) >= 0;

It's not clear in your question if ranges that end or start on the same date are considered overlapping. If they are not then you can change then use < and > rather than <= and >=.

Update

As @BasilBorque points out, the classes above have been superseded by those in java.time. A better solutions now would be:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/DD/YYYY");
LocalDate startDate = LocalDate.parse("11/03/2016", formatter);
LocalDate endDate = LocalDate.parse("11/23/2016", formatter);
sprinter
  • 27,148
  • 6
  • 47
  • 78
  • This is old-school advice. Those are troublesome old date-time classes, now legacy, supplanted by the java.time classes. Furthermore this code is using date-time values when the question asks for date-only values. – Basil Bourque Nov 04 '16 at 06:17