In Java, we might need to perform various modifications on the dates, such as adding or subtracting days from them, to know the future scheduled date or the past. In this article, we will see how to add days to a date in Java.
Using the Calendar class
Java util provides a Calendar class, which is used to manipulate dates and times. We can use a method add()
to add the number of days to a date.
Following is an example:
import java.util.*;
public class AddDaysToCalendarExample {
public static void main(String[] args) {
// Create a Calendar instance
Calendar calendar = Calendar.getInstance();
// Set the date to a specific date
calendar.set(2023, Calendar.JUNE, 15);
// Adding 5 days
int daysToAdd = 5;
calendar.add(Calendar.DAY_OF_MONTH, daysToAdd);
// Get the updated date
Date newDate = calendar.getTime();
System.out.println("Original Date: " + new Date());
System.out.println("New Date after adding " + daysToAdd + " days: " + newDate);
}
}
Explanation:
After running the above code, you’ll see the original date and the new date after adding the specified number of days.
Java 8 or later
If you are using Java 8 or later, you can use the java.time package, which provides more modern APIs to manipulate the date and time.
In Java8, The LocalDate
class inside the java.time package allows for simpler date manipulation, including adding days.
Following an example:
import java.time.*;
public class AddDaysToLocalDateExample {
public static void main(String[] args) {
// Create a LocalDate instance
LocalDate currentDate = LocalDate.of(2023, Month.JUNE, 15);
// Adding 5 days
int daysToAdd = 5;
LocalDate newDate = currentDate.plusDays(daysToAdd);
System.out.println("Original Date: " + currentDate);
System.out.println("New Date after adding " + daysToAdd + " days: " + newDate);
}
}
References:
https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html