First, validation rules are not run from within triggers. I'm assuming you mean that you want to compare dates to do your own validation of some kind within a trigger.
The Date Class function that will most likely be of use to you is daysBetween(Date)
.
Example:
Date startDate =
Date.newInstance(2008, 1, 1);
Date dueDate =
Date.newInstance(2008, 1, 30);
Integer numberDaysDue =
startDate.daysBetween(dueDate);
Note: there's also a monthsBetween(date)
method.
Another method that might be of use is isSameDay(Date)
.
Example:
date myDate = date.today();
date dueDate =
date.newInstance(2008, 1, 30);
boolean dueNow = myDate.isSameDay(dueDate);
There are other methods in the Date Class that you might find helpful in sorting your dates by Year, month and day depending on what appeals to you such as year()
and dayOfYear()
.
EDIT
Here's some sample code to get you started. There are any number of ways one could approach this, what I'm showing is just one of them.
The issue you're going to have is one of mapping your dates. So, it might be worth converting the start date to a "datePlus" where you have the StartDate and the number of days between it and the End Date.
map<Id,date>StDateMap = new map<Id, date>();
map<Id,integer>DayBtwnMap = new map<Id, integer>();
integer DaysBtwn = 0;
for(CustOb rc:Records){
DaysBtwn = rc.StartDate.daysBetween(rc.EndDate);
StDateMap.put(rc.Id,rc.StartDate);
DayBtwnMap.put(rc.Id,DaysBtwn);
}
That gets all of your data into maps. Now you'll have to sort the map to get the start dates in seqence (if they're not already).
If they are, or once you have them in sequence, then you'd run a loop that would look something like the one below where you'd test the start date first (Remember that its possible an inserted end date could cause an overlap too, so you may want to factor the record's date into your criteria as this is non-determinant as to which record was entered first).
Its also possible these two methods could be combined and performed at the same time, but I didn't want to confuse anyone by doing that.
set<Id>SDkeys = new set<Id>();
SDkeys = StDateMap.keyset();
List<Id>ErrLst = new List<Id>();
for (i=0,i=SDkeys.size(),i++){
if(i<SDkeys.size()){
if(StDateMap.get(SDkeys(i)).daysBetween(StDateMap.get(SDkeys(i+1))) < DaysBtwn.get(SDkeys(i)){
ErrLst.add(SDkeys(i+1);
i++; // increment i to skip the ID you just eliminated
}
}
}