Java检查新日期范围是否在其他日期范围之间下降/交叉

时间:2016-06-01 19:20:22

标签: java validation date compare

我需要确定日期范围是否在其他日期范围内/跨越。例如:

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 1: 01/01/2016 - 05/31/2016
Existing 2: 06/05/2017 - 10/31/2017

如果我的新日期下降/跨越现有日期,我应该生成错误消息。这是我现有的代码(没有按预期工作):

for (Period p : periodList) {
    if (!(newPeriodStartDate.after(p.getExistingPeriodStartDate())) 
        && !(newPeriodStartDate.before(p.getExistingPeriodEndDate()))) {
            message = "The Period falls between an existing Period: "+p.periodName();
            break;
    }
    if (newPeriodEndDate.after(p.getExistingPeriodStartDate()) 
        && newPeriodEndDate.before(p.getExistingPeriodEndDate())) {
         if (message == null) {
            message = " The Period falls between an existing Period: "+p.getPeriodName();
         }
            break;
    }
}

修改

更新了代码(仍无效)。我错过了什么:

if (!(newPeriodStartDate.getTime() <= p.getExistingPeriodEndDate().getTime())
                                        && (newPeriodEndDate.getTime() <= p.getExistingPeriodStartDate().getTime())) {
   ...
}

编辑2:

这是一个重复的问题,但这个问题的答案并没有解决我的问题。博文(http://baodad.blogspot.com/2014/06/date-range-overlap.html)帮助我解决了问题。

1 个答案:

答案 0 :(得分:0)

最后,这有效:

 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;
            }
        }