You are on page 1of 2

package com.bhagin.pocs.

misc;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.SortedSet;
import java.util.TreeSet;

/**
* @date 10 Mar, 2011
* @author rohitmp
*/
public class SeqPeriods {

public boolean arePeriodsSequential(final ArrayList<Period> arlOfPeriods)


throws IllegalArgumentException {
SortedSet <Calendar> setOfCals = new TreeSet<Calendar>();
long sumOfPeriods = 0;
for (Period period : arlOfPeriods) {
Calendar startDt = period.getStartDate();
Calendar endDt = period.getEndDate();
long startDtNoOfDaysSinceEpoch = 0;
long endDtNoOfDaysSinceEpoch = 0;

if(startDt != null){
startDtNoOfDaysSinceEpoch = getNoOfDaysSinceJavaEpoch(startDt);
setOfCals.add(startDt);
} else {
throw new IllegalArgumentException("The date cannot be null");
}
if(endDt != null){
endDtNoOfDaysSinceEpoch = getNoOfDaysSinceJavaEpoch(endDt);
setOfCals.add(endDt);
} else {
throw new IllegalArgumentException("The date cannot be null");
}

sumOfPeriods += ((endDtNoOfDaysSinceEpoch - startDtNoOfDaysSinceEpoch +


1) *
(endDtNoOfDaysSinceEpoch +
startDtNoOfDaysSinceEpoch))/2;

Calendar minDt = setOfCals.first();


Calendar maxDt = setOfCals.last();

long minDtSinceEpoch = getNoOfDaysSinceJavaEpoch(minDt);


long maxDtSinceEpoch = getNoOfDaysSinceJavaEpoch(maxDt);
long validSumOfDates = ((maxDtSinceEpoch - minDtSinceEpoch + 1)*
(maxDtSinceEpoch + minDtSinceEpoch))/2;
if(sumOfPeriods == validSumOfDates){
return true;
} else {
return false;
}
}

private long getNoOfDaysSinceJavaEpoch(Calendar date) {


Calendar calEpoch = Calendar.getInstance();
calEpoch.set(1970, Calendar.JANUARY, 1);

long lCalEpoch = calEpoch.getTimeInMillis();


long lCal1 = date.getTimeInMillis();

long noOfDaysSinceEpoch = (lCal1-lCalEpoch)/(1000*24*60*60);


return noOfDaysSinceEpoch;
}

} //end of class SeqPeriods

You might also like