Subtract Days from a Date in Java
Subtracting Days From a Date in Java
Working with date-time values in Java can be confusing, especially if you need to subtract days from a date. But using the right methods, it's really quite simple. In this article, we'll show you how to subtract days from a date in Java.
Using java.util.Calendar
The most straightforward approach to subtracting days from a date is to use the java.util.Calendar class. This class has many methods for working with dates, but for our purposes, we'll be using the add() and subtract() methods. The add() method adds a specified amount of time to a date, while the subtract() method subtracts a given number of days.
First, let's initialize a Calendar object with our date:
Calendar calendar = Calendar.getInstance(); calendar.set(2019, 0, 15); // 15 Jan 2019
Next, we can subtract one day from our date by calling the subtract() method. We pass in the Calendar.DAY_OF_MONTH constant, along with the number of days to subtract. In this case, we want to subtract one day, so we pass in the value 1:
calendar.subtract(Calendar.DAY_OF_MONTH, 1); // 14 Jan 2019
We can also use the add() method to subtract days from a date. Instead of passing a positive number of days to add, we pass in a negative number of days. For example, to subtract two days, we pass in the value -2:
calendar.add(Calendar.DAY_OF_MONTH, -2); // 12 Jan 2019
Using java.time.LocalDate
If you're using Java 8 or later, you have access to the newer java.time API. This API offers a variety of classes for working with date-times, including the LocalDate class. To subtract days from a date, you can use the minusDays() method.
First, let's create a LocalDate object for our date:
LocalDate date = LocalDate.of(2019, 1, 15); // 15 Jan 2019
Now, we can subtract one day from our date by calling the minusDays() method, passing in the number of days to subtract. In this case, we want to subtract one day, so we pass in the value 1:
date = date.minusDays(1); // 14 Jan 2019
Similarly, we can subtract two days by passing in the value 2:
date = date.minusDays(2); // 12 Jan 2019
Conclusion
In this article, we discussed two methods for subtracting days from a date in Java. First, we used the java.util.Calendar class and its add() and subtract() methods. Then, we used the java.time API to subtract days with the minusDays() method. Regardless of which approach you choose, it's important to remember to always specify the correct number of days to subtract.