6

I have 2 object. They both have a start date and an end date. How can I check if they overlap?

now I have:

if((item1.DateStart__c >= item2.DateStart__c && item1.DateStart__c <= item2.DateEnd__c) ||
    (item1.DateEnd__c >= item2.DateStart__c && item1.DateEnd__c <= item2.DateEnd__c) ||
    (item1.DateStart__c <= item2.DateStart__c && item1.DateEnd__c >= item2.DateEnd__c)) {

    //error
}

This does not work...

6
  • What is the error?? Commented Jul 9, 2014 at 13:43
  • If you mean the error I want to give, it's just an error to say that is overlapping.
    – Thomas
    Commented Jul 9, 2014 at 13:44
  • Ahhh...my misunderstanding. I thought you were saying you were receiving an error. My mistake Commented Jul 9, 2014 at 13:46
  • Thank you for your time. I'm not getting an error message, I'm trying to give one ! :)
    – Thomas
    Commented Jul 9, 2014 at 13:47
  • So, is there a specific scenario its not working for?? It looks like it should work for certain scenarios. Can you isolate which cases its not working for? Commented Jul 9, 2014 at 13:54

2 Answers 2

2

Looks like its just a typo. In your 3rd scenario, you are comparing item1.DateEnd__c to itself. You just need to change it to item2.DateEnd__c

if((item1.DateStart__c >= item2.DateStart__c && item1.DateStart__c <= item2.DateEnd__c) ||
    (item1.DateEnd__c >= item2.DateStart__c && item1.DateEnd__c <= item2.DateEnd__c) ||
    (item1.DateStart__c <= item2.DateStart__c && item1.DateEnd__c >= item2.DateEnd__c)) {

    //error
}
2
  • Excuse me.. that would be a typo. My apologies.
    – Thomas
    Commented Jul 9, 2014 at 14:00
  • No worries. Happens to the best of us. Always good to get another set of eyes on it. Thats what we are here for :) Commented Jul 9, 2014 at 14:00
2

I would recommend reading this post: https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap

Overall, what you need to do is set up logic as below. This will always result in finding overlapping dates.

if(item1.DateStart__c <= item2.DateEnd__c && item1.DateEnd__c >= item2.DateStart__c){
    //error
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .