Saturday, 27 December 2014

Count of Days, Months and Years

/*
 * @author Himabindu
 * When you pass start date & end date to the function, it returns a map which contain number of days,number of months
 * & years will return
 *
 */

def getDatesCountMap(startDate, endDate){

int[] monthDay = [ 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
Calendar fromDate
Calendar toDate
def increment = 0
def year
def int month
def int day

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

def p1 = startDate + " 00:00:00"
def p2 = endDate + " 00:00:00"

Date start = format.parse(p1)
Date end = format.parse(p2)

Calendar d1 = new GregorianCalendar().getInstance();
d1.setTime(start);

Calendar d2 = new GregorianCalendar().getInstance();
d2.setTime(end);

if (d1.getTime().getTime() > d2.getTime().getTime()) {
fromDate = d2;
toDate = d1;
} else {
fromDate = d1;
toDate = d2;
}

if (fromDate.get(Calendar.DAY_OF_MONTH) > toDate.get(Calendar.DAY_OF_MONTH)) {
increment = monthDay[fromDate.get(Calendar.MONTH)];
}

GregorianCalendar cal = new GregorianCalendar();
boolean isLeapYear = cal.isLeapYear(fromDate.get(Calendar.YEAR));

if (increment == -1) {
if (isLeapYear) {
increment = 29;
} else {
increment = 28;
}
}

// DAY CALCULATION
if (increment != 0) {
day = (toDate.get(Calendar.DAY_OF_MONTH) + increment) - fromDate.get(Calendar.DAY_OF_MONTH);
increment = 1;
} else {
day = toDate.get(Calendar.DAY_OF_MONTH) - fromDate.get(Calendar.DAY_OF_MONTH);
}

// MONTH CALCULATION
if ((fromDate.get(Calendar.MONTH) + increment) > toDate.get(Calendar.MONTH)) {
month = (toDate.get(Calendar.MONTH) + 12) - (fromDate.get(Calendar.MONTH) + increment);
increment = 1;
} else {
month = (toDate.get(Calendar.MONTH)) - (fromDate.get(Calendar.MONTH) + increment);
increment = 0;
}

// YEAR CALCULATION
year = toDate.get(Calendar.YEAR) - (fromDate.get(Calendar.YEAR) + increment);

def dateMap = [:]

dateMap.days = day
dateMap.month = month
dateMap.year = year
return dateMap
}

No comments:

Post a Comment