Sunday, 9 November 2014

To find days elapsed between two valid dates

//To find days elapsed between two valid dates
import java.util.* ;
class DateQ2_2000 {
static int daysOfMonth[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
static void validateInput(int d,int m,int y){ // validates the input date
if(y<1 || y>9999) {
System.out.println("INVALID YEAR");
System.exit(0);

}
if(m<1 || m>12) {
System.out.println("INVALID MONTH");
System.exit(0);
}
if(d<1 || d>daysOfMonth[m]) {
System.out.println("INVALID DAY");
System.exit(0);

}
}
static boolean isLeap(int y){
if((y%4==0 && y%100!=0)|| y%400==0) return true;
return false;
}
static int daysBefore(int d,int m,int y){
// finds days elapsed from start date till end of first year
int diff=0,i;
if(isLeap(y))
daysOfMonth[2]+=1; // check for days in February
diff=daysOfMonth[m]-d; // find remaining last days of start month
for(i=m+1;i<=12;i++)
diff+=daysOfMonth[i]; // find days till last month of first year
return diff;
}
static int daysBetween(int y1,int y2){
// finds days elapsed between start year and finish year
int diff=0,i;
for(i=y1+1;i<=y2-1;i++)
if(isLeap(i)) diff+=366;
else diff+=365;
return diff;
}
static int daysAfter(int d,int m,int y){
// finds days elapsed from beginning of finish year till finish date
int diff=0,i;
if(isLeap(y))
daysOfMonth[2]+=1; // check for days in February
for(i=1;i<m;i++)
diff+=daysOfMonth[i]; // find days till last month of first year
diff+=d;
return diff;
}
public static void main(String args []) throws Exception {
Scanner sc=new Scanner(System.in);
int dd1,mm1,yy1,dd2,mm2,yy2,i,days;
System.out.print("First Date:\t");
System.out.print("\tDay: ");
dd1=sc.nextInt();
System.out.print("\t\t\t\tMonth: ");
mm1=sc.nextInt();
System.out.print("\t\t\t\tYear: ");
yy1=sc.nextInt();
System.out.print("\nSecond Date:\t");
System.out.print("Day: ");
dd2=sc.nextInt();
System.out.print("\t\t\t\tMonth: ");
mm2=sc.nextInt();
System.out.print("\t\t\t\tYear: ");
yy2=sc.nextInt();
days=0;
validateInput(dd1,mm1,yy1); // validate first date
validateInput(dd2,mm2,yy2); // validate second date
if(yy1==yy2){ // if dates are of same year
if(isLeap(yy1))
daysOfMonth[2]+=1; // check for days in February
days=daysOfMonth[mm1]-dd1; // find remaining last days of start month
for(i=mm1+1;i<mm2;i++)
days+=daysOfMonth[i]; // find days between start and finish month
days+=dd2; // add beginning days of finish month
}
else { //  dates are of different years

int diff1=daysBefore(dd1,mm1,yy1);
int diff2=daysBetween(yy1,yy2);
int diff3=daysAfter(dd2,mm2,yy2);
days=diff1+diff2+diff3;
}
System.out.println("\nOUTPUT :");
System.out.print("\nDays elapsed: "+days);
} // end of main
} // end of class 

No comments:

Post a Comment