validation - Java Check if a new date range falls/crossovers between other date ranges -
this question has answer here:
- determine whether 2 date ranges overlap 32 answers
i need determine if date range within/cross on other date ranges. eg:
new start date 1: 12/01/2015 (mm/dd/yyyy) new start date 2: 03/01/2016 --> throw error message
new start date 1: 12/01/2016 new start date 2: 12/01/2017 --> throw error message
existing date ranges:
existing 1: 01/01/2016 - 05/31/2016 existing 2: 06/05/2017 - 10/31/2017
i should generate error message if new dates fall/crossover existing dates. here existing code (not working expected):
for (period p : periodlist) { if (!(newperiodstartdate.after(p.getexistingperiodstartdate())) && !(newperiodstartdate.before(p.getexistingperiodenddate()))) { message = "the period falls between existing period: "+p.periodname(); break; } if (newperiodenddate.after(p.getexistingperiodstartdate()) && newperiodenddate.before(p.getexistingperiodenddate())) { if (message == null) { message = " period falls between existing period: "+p.getperiodname(); } break; } }
edit
updated code (still not working). missing:
if (!(newperiodstartdate.gettime() <= p.getexistingperiodenddate().gettime()) && (newperiodenddate.gettime() <= p.getexistingperiodstartdate().gettime())) { ... }
edit 2:
this duplicate question, answer question did not fix issue. blog post (http://baodad.blogspot.com/2014/06/date-range-overlap.html) helped me fix.
finally, worked:
boolean isoverlapped(date newstartdate, date newenddate, date existingstartdate, date existingenddate) throws nullpointerexception{ if (!((newenddate.gettime() <= existingstartdate.gettime()) || (newstartdate.gettime() >= existingenddate.gettime()))) { return true; } else { return false; } }