Wednesday, April 20, 2011

From & To date range

Following snippet will be useful if you need the date range i.e. fixed From & To date. This will return you the List of Date objects by filtering the Saturday & Sunday’s.

We have date many types, we consider here as ‘DD-Mon-YYYY’ Type only.
Hence calling to following method should be like,

List fromToDateList = getFromToDateRange(”22-Jan-2011″,”10-Feb-2011″);

If you need different type of date format, then you can change it simply by defining the SimpleDateFormat object.
Main concept is whichever format date you passing, convert it into the Date object & set it into the Calendar Object, so that we can process it easily.

public static List getFromToDateRange( final String strFromDate, final String strToDate) throws Exception
{
List dateRangeList = new ArrayList();
Calendar calFromDate = Calendar.getInstance();
Calendar calToDate = Calendar.getInstance();
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(”dd-MMM-yyyy”);

try
{
Date fromDate = simpleDateFormat.parse( strFromDate );
Date toDate = simpleDateFormat.parse( strToDate );
boolean loopFlag = true ;
calFromDate.setTime( fromDate );
calToDate.setTime( toDate );

int fromDayOfWeek = calFromDate.get(Calendar.DAY_OF_WEEK);
if(fromDayOfWeek != Calendar.SUNDAY && fromDayOfWeek != Calendar.SATURDAY)
{
dateRangeList.add( fromDate );
}

if( fromDate.before( toDate ))
{
while(loopFlag)
{
calFromDate.add( Calendar.DATE, 1 );

boolean fromToDateEqual = calFromDate.getTime().equals( calToDate.getTime() );

int dayOfWeek = calFromDate.get(Calendar.DAY_OF_WEEK);

if( !fromToDateEqual && dayOfWeek != Calendar.SUNDAY && dayOfWeek != Calendar.SATURDAY)
{
dateRangeList.add( calFromDate.getTime() );
}

if( fromToDateEqual )
{
loopFlag = false;
}
}
}

int toDayOfWeek = calToDate.get(Calendar.DAY_OF_WEEK);
if(toDayOfWeek != Calendar.SUNDAY && toDayOfWeek != Calendar.SATURDAY)
{
dateRangeList.add( toDate );
}

}
catch(Exception exc)
{
throw new Exception(”Exception while formatting the date range between From & To date ::” + exc);
}

return dateRangeList;
}

No comments: