Program opened below. You can scroll through the algorithm, Java code and output.
Program 30
Difference Between Two Dates
Question
Read two valid Gregorian dates as day, month, year. Calculate their absolute difference in days without date-library methods.
Algorithm
Step 1: Start and accept day, month and year of the first date.
Step 2: Accept day, month and year of the second date.
Step 3: Define Gregorian leap-year checking rules.
Step 4: A year divisible by 400 is a leap year.
Step 5: A year divisible by 100 but not 400 is not a leap year.
Step 6: Other years divisible by four are leap years.
Step 7: Determine the number of days in each requested month.
Step 8: Validate both month values and both day values.
Step 9: Reject invalid dates or years before year one.
Step 10: For each date, count days in all preceding complete years.
Step 11: Add leap days occurring before that year.
Step 12: Add the days in earlier months of the current year.
Step 13: Add the current day to obtain the date serial number.
Step 14: Subtract the two serial numbers and take the positive magnitude.
Step 15: Display the difference in days and stop.
Java program
Javaimport java.util.*;
class DateDifference {
static boolean leap(int y) {
return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0);
}
static int monthDays(int m, int y) {
int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
if (m == 2 && leap(y)) {
return 29;
}
return days[m - 1];
}
static boolean valid(int d, int m, int y) {
return y >= 1 && m >= 1 && m <= 12 && d >= 1 && d <= monthDays(m, y);
}
static long serial(int d, int m, int y) {
long years = y - 1;
long total = 365 * years + years / 4 - years / 100 + years / 400;
for (int i = 1; i < m; i++) {
total += monthDays(i, y);
}
return total + d;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int d1 = sc.nextInt();
int m1 = sc.nextInt();
int y1 = sc.nextInt();
int d2 = sc.nextInt();
int m2 = sc.nextInt();
int y2 = sc.nextInt();
if (!valid(d1, m1, y1) || !valid(d2, m2, y2)) {
System.out.println("Invalid date");
return;
}
long difference = serial(d1, m1, y1) - serial(d2, m2, y2);
if (difference < 0) {
difference = -difference;
}
System.out.println("Days = " + difference);
}
}Sample output
Input: 1 1 2024 3 1 2024
Output: Days = 2
ADDITIONAL UNIQUE PRACTICALS
Index of additional programs