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 codeimport 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 codeEnter 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.
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0