Days Before N Days

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 17:- Days Before N Days

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.

4. Operators

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?