If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To calculate the date N days before a given date, you can use the java.time.LocalDate
class introduced in Java 8, which provides convenient methods for date manipulation. Here's a Java program to find the date N days before a specified date:
javaCopy code
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class DaysBeforeN {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input date from the user
System.out.print("Enter a date (yyyy-MM-dd): ");
String inputDateStr = scanner.next();
// Parse the input date to LocalDate object using the specified format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate inputDate = LocalDate.parse(inputDateStr, formatter);
// Get the number of days before the input date
System.out.print("Enter the number of days before: ");
int daysBefore = scanner.nextInt();
// Calculate the date N days before the input date
LocalDate resultDate = inputDate.minusDays(daysBefore);
// Print the result date
System.out.println("The date " + daysBefore + " days before " + inputDate + " is " + resultDate);
scanner.close();
}
}
Example output:
yamlCopy code
Enter a date (yyyy-MM-dd): 2023-07-31
Enter the number of days before: 10
The date 10 days before 2023-07-31 is 2023-07-21
In the program above, we take the user input for the date in the format "yyyy-MM-dd" and parse it into a LocalDate
object using the DateTimeFormatter
. Then, we take the input for the number of days before and use the minusDays()
method of the LocalDate
class to calculate the date N days before the input date. Finally, we print the result date to the console.
Note that if the resulting date falls before the minimum supported date (January 1, 0001), you may encounter an exception. Be sure to handle such cases accordingly if needed.
Comments: 0