Thursday, March 1, 2007

Date Utilities

Some methods for date calcuations..

public class DateUtils {

public static final String DATE_FORMAT = "dd/MM/yyyy";


/** * This method gives difference(number of days) in two dates.
* @param newDate
* @param oldDate
* @return
* @throws Exception
*/
public static int dateDiff (String newDate, String oldDate) throws Exception{

int noOfDays = 0;
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
Date date1 = new SimpleDateFormat(DATE_FORMAT).parse(newDate);
Date date2 = new SimpleDateFormat(DATE_FORMAT).parse(oldDate);
long diff = date1.getTime() - date2.getTime();
if (diff > 0) {
noOfDays = (int)(diff/MILLIS_IN_DAY);
}
return noOfDays;
}


/**
* This method subtracts given number of days from specified date
* and returns resultant date as a string.

* @param newDate
* @param days
* @return
* @throws Exception
*/

public static String subtractDaysFromDate (String newDate,int days) throws Exception
{
Date date1 = new SimpleDateFormat(DATE_FORMAT).parse(newDate);
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
long diff = date1.getTime() - MILLIS_IN_DAY;
Date tempDate1 = new Date(diff);
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
String returnString = format.format(tempDate1);
return returnString;
}
/**
* This method adds given number of days to specified date and returns result date.
* @param strDate
* @param days
* @return
* @throws Exception
*/
public static String addDaysToDate (String strDate , int days) throws Exception{
String strDateNew = "";
Date tempDate = new SimpleDateFormat
(DATE_FORMAT).parse(strDate);
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
Calendar cal = Calendar.getInstance();
cal.setTime(tempDate);
cal.add(Calendar.DATE,days);
Date tempDate1 = new Date(cal.getTimeInMillis());
strDateNew = format.format(tempDate1);
return strDateNew;
}

No comments: