Program opened below. You can scroll through the algorithm, Java code and output.
Program 45
Find the Past Date
Question
Accept a date and a number of days, then calculate the date that many days earlier.
Algorithm
Step 1: Start the program and accept the date in dd/mm/yyyy format.
Step 2: Locate the slash separators and extract the day, month and year.
Step 3: Convert the extracted parts into integer values.
Step 4: Check whether the year is a leap year using the 400-year and 4/100-year rules.
Step 5: Prepare the number of days in each month and adjust February for the year.
Step 6: Check that the month, day and year form a valid date.
Step 7: If the date is invalid, display an error and stop.
Step 8: Accept the number of days to subtract from the given date.
Step 9: Decrease the day by one for each day to be subtracted.
Step 10: If the day becomes zero, move to the previous month.
Step 11: Set the day to the last day of that previous month.
Step 12: When moving before January, change the year and set the month to December.
Step 13: Recalculate February's length if the year changes.
Step 14: Display the resulting past date in dd/mm/yyyy format and stop.
Java program
Javaimport java.util.*;
class PastDate
{
static boolean leap(int y)
{
return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0);
}
static int daysInMonth(int m, int y)
{
int[] days = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if (m == 2 && leap(y))
{
return 29;
}
return days[m];
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter date (dd/mm/yyyy): ");
String date = sc.nextLine();
String[] p = date.split("/");
int d = Integer.parseInt(p[0]);
int m = Integer.parseInt(p[1]);
int y = Integer.parseInt(p[2]);
System.out.print("Days before: ");
int n = sc.nextInt();
if (m < 1 || m > 12 || d < 1 || d > daysInMonth(m, y) || n < 0)
{
System.out.println("Invalid input");
return;
}
for (int i = 0; i < n; i++)
{
d--;
if (d == 0)
{
m--;
if (m == 0) { m = 12;
y--;
}
d = daysInMonth(m, y);
}
}
System.out.printf("Past date: %02d/%02d/%04d%n", d, m, y);
}
}Sample output
Input: Input: 03/01/2000; days before: 5
Output: Past date: 29/12/1999