Find the number of days elapsed between two dates

Find The Number Of Days Elapsed Between Two Dates


WAP to enter two dates of the same year and find the number of days elapsed between them.
/* Enter two dates of the same year and find the
 * number of days elapsed between them
 */

import java.util.*;
class TwoDateDiff
{
public static void main (String args[])throws InputMismatchException
{
Scanner scan = new Scanner(System.in);

int d1,m1,d2,m2,y,i,total1,total2,diff;

    System.out.println("Enter the day and month of first date: ");
    d1 = scan.nextInt();
    m1 = scan.nextInt();

    System.out.println("Enter the day and month of second date: ");
    d2 = scan.nextInt();
    m2 = scan.nextInt();

    System.out.println("Enter the year: ");
    y = scan.nextInt();


    int dom[] = {31,28,31,30,31,30,31,31,30,31,30,31};

   //If it is a leap year, februrary should have 29 days.     
    if(y%4 == 0)
        dom[1] = 29;

     // Check for validity of date
    if(d1 < 0 || m1 > 12 || d1 > dom[m1-1] || d2 < 0 || m2 >12 || d2 > dom[m2-1]){
        System.out.println("Please enter a valid date.");
    }else{



        total1 = 0;
    //Add the days of the month
        for(i=0; i< m1-1; i++)
            total1 += dom[i];

    //Add the days of the current month
     total1+=d1;  

     total2 = 0;
    //Add the days of the month
        for(i=0; i< m2-1; i++)
            total2 += dom[i];

    //Add the days of the current month
     total2+=d2;

  diff = (int) Math.abs(total1 - total2);  

  System.out.println("Days elapsed : "+diff);
}//else

}//end of main
}//end of class

Have something to say? Log in to comment on this post.

0 comments