**Write a program to input 2 dates and print the number of days between them also count the number of months and days between them.**

Example 1:

Enter the day, month and year for the first date:

12

4

2014

Enter the day, month and year for the second date:

11

7

2018

Number of days: 1551

Number of months: 50 Days: 29

Example 2:

Enter the day, month and year for the first date:

28

4

2016

Enter the day, month and year for the second date:

4

5

2016

Number of days: 6

Number of months: 0 Days: 6

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
import java.util.*; public class DateDays { int md[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; boolean isLeap(int y) { if(y%4==0&&y%100!=0||y%400==0)//Checking conditions for leap year return true; return false; } boolean isValid(int d, int m, int y) { if(d<1||m<1||y<0||m>12||d>31)//Checking invalid conditions return false; if((m==4||m==6||m==9||m==11)&&d>30) return false; if(m==2&&isLeap(y)&&d>29) return false; if(m==2&&!isLeap(y)&&d>28) return false; return true; /*If none of the above conditions are true then the Date is a valid date*/ } void days(int d1, int m1, int y1, int d2, int m2, int y2) { int m = m1, y = y1, cm=0; if(isLeap(y1)) md[2] = 29; int s =0, sd = md[m1]-d1 + d2, i; m=m+1; if(m1==m2&&y1==y2) //When the month and year is same in both dates { s = d2 - d1; sd = d2 - d1; } else { do { if(m>12) { /*If the month is more than 12 then the month should be changed to 1 and the year increased by 1*/ m = 1; y++; } if(isLeap(y)) //If the current year is leap then the number md[2] = 29; //of days should be 29 else 28 else md[2] = 28; if(m==m2&&y==y2) break;/*If the counter month and year has reached the destination month and year then the loop should be terminated*/ s = s+md[m]; //Adding the number of days of the current month m++; //Incrementing the number of month by 1 cm++; //Counting the number of months }while(true); s = s+sd; /*Adding the remaining days from the first date and the days in the destination date*/ } if(sd>=md[m1]) { cm++; //If the extra days is more than the number of days in //the starting month then the counter should increase //by 1 sd = sd-md[m1]; } System.out.println("Number of days: "+s); System.out.println("Number of months: "+cm+"\tDays: "+sd); } public static void main() { Scanner sc = new Scanner(System.in); int d1,d2,m1,m2,y1,y2; System.out.println("Enter the day, month and year for the first date: "); d1 = sc.nextInt(); m1 = sc.nextInt(); y1 = sc.nextInt(); System.out.println("Enter the day, month and year for the second date: "); d2 = sc.nextInt(); m2 = sc.nextInt(); y2 = sc.nextInt(); DateDays ob = new DateDays(); ob.days(d1,m1,y1,d2,m2,y2);//Calling the function } } |

## Leave a Reply