Here's the program:
class DateDiff {
int month[];//stores the number of days in all the months
int d,y,m,n;
DateDiff(int d,int m,int y) {
month=new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
this.d=d;
this.m=m;
this.y=y;
if(isLeap(y))
month[1]=29;//if year is leap, February has 29 days
else
month[1]=28;
n=0;
}
//function for checking for Leap Year
boolean isLeap(int y3) {
if((y3%400==0) || ((y3%100!=0)&&(y3%4==0)))
return true;
else
return false;
}
//function for finding the number of days that have passed from start of the year
int getDayNum(int d1,int m1,int y1) {
int i=0;
if(isLeap(y1))//February leap year correction
month[1]=29;
else
month[1]=28;
for(;i<m1;i++)
if(d<=month[i]&&i==m1-1) {
n+=d1;//add days when month hasn't completed
break;
}
else
n+=month[i]; //add the normal number of days in the month
return n;
}
//finding difference between the dates
int diff(int d2,int m2,int y2) {
int daysLeft=getDayNum(d,m,y);//store the number of days passed since start of the year y
if(isLeap(y))
daysLeft=366-daysLeft;//subtracting gives the number of days left in year y
else
daysLeft=365-daysLeft;
for(int x=y+1;x<y2;x++)//for subsequent years add 366 or 365 days as required
if(isLeap(x))
daysLeft+=366;
else
daysLeft+=365;
daysLeft+=getDayNum(d2,m2,y2);//add the number of days that have passed since start of year y2
return daysLeft;}}
public class DateDifference{
public static int main(int d1,int m1,int y1,int d2,int m2,int y2) {
DateDiff obj=new DateDiff(d1,m1,y1);
return obj.diff(d2,m2,y2);
}
}
I'm not getting the correct output with this program. Pass d1=20,m2=3,y1=1997
and d2=14,m2=2,y2=2015
( the dates are 20th March 1997 and 14th February 2015).
The correct difference is 6540 days. My program gives 6619 days. Can somebody point out the error please?