Header Ad

Saturday, January 19, 2008

Date Difference between Two Dates

The following program is to get the Date Difference in days.Here we have to provide two date fields which are of date time type(contains both date and time).


import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;



public class DateDifference
{
public static int getDaysinMonth(int year, int month)
{
int days=0;
int nly[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int ly[] = {31,29,31,30,31,30,31,31,30,31,30,31};
int y[];
if (year%4 == 0)
y=ly;
else
y=nly;

for (int intIndex=0;intIndex<month;intIndex++)
{
days = days+y[intIndex];
}
return days;
}

public static long getDays(String date[])
{
long days = 0;
int date1[]={0,0,0};
for (int intIndex=0;intIndex<date.length;intIndex++)
{
date1[intIndex] = Integer.parseInt(date[intIndex].trim());
}
days = (((date1[0]-1)/4)+1)*366 + ((date1[0]-1)-(((date1[0]-1)/4)+1)) * 365;
days = days + getDaysinMonth(date1[0],date1[1]-1);
days = days + (date1[2] - 1);
return days;
}

public static void main(String[] args)
{
long lngDateDiffinDays=0;
Date1=Date1.trim();
String date_time1[] = Date1.split(" ");
String date1[] = date_time1[0].split("-");
long days1 = getDays(date1);
Date2=Date2.trim();
String date_time2[] = Date2.split(" ");
String date2[] = date_time2[0].split("-");
long days2 = getDays(date2);

lngDateDiffinDays=days1-days2;
}

}

No comments: