Java Subtract Days from Current Date
In Java, dealing with date and time is not much difficult task because Java provides API for date and time that makes tasks easier for the developers.
In this section, we will discuss how to subtract number of days from current date and any particular day.
Using Java Calendar Class
In the following Java program, we have used the Java Calendar class. In order to get the current date first, we have created an instance of the Calendar class, after that called the getTime() method that prints the current date and time on the console.
Now let's subtract the days by calling the add() method and Calendar.DATE constant. In this method, we have passed a negative value because we are subtracting days from the current date.
In the same way, we can also add days to the current date. Note that the number of days must be positive. Let's implement the above logic in a Java program.
Current Date = Mon Feb 14 19:15:55 GMT 2022 Updated Date = Fri Feb 11 19:15:55 GMT 2022
Instead of using the DATE field, we can also use the DAY_OF_YEAR field to get the current date. Consider the following program.
Current Date: Mon Feb 14 20:03:50 GMT 2022 Date before 100 days: Sat Nov 06 20:03:50 GMT 2021
Using Java LocalDate Class
Java 8 introduces a new DateTime API for manipulating date and time. The API provides many Java classes. But one of the most useful class in this API is the LocalDate class, for holding a date value. It belongs to java.time package.
In the following Java program, we have used the parse() method of the LocalDate class. It is used to get an instance of the LocalDate from a string such as '2022-02-14' as a parameter. Note that the string must be a valid date-time format.
The class also provides a method minusDays() that is used to subtract number of days from the current date.
The syntax of the minusDays() method is as follows:
The method accepts a long value that represents the number of days subtract from the current date. Note that the number of days to subtract may be positive and negative. It returns a copy of date after subtracting the days. It throws DateTimeException if the result exceeds the supported date range.
The following Java program subtract days from current date.
Date: 2022-02-14 New Date: 2021-12-20
The following Java program subtract days from a specified date.
Date: 2022-02-11 New Date: 2022-01-30
In the above program, we can also change time zone. Consider the following program for the same.
New Date: 2022-01-15
Next TopicJava Future Example