How to Add Days to Date in Java: Simple Guide
In Java, you can add days to a date using the
java.time.LocalDate class and its plusDays() method. This method returns a new LocalDate with the specified number of days added, keeping the original date unchanged.Syntax
Use the plusDays(long daysToAdd) method of the LocalDate class to add days to a date.
LocalDate: Represents a date without time.plusDays(): Adds the given number of days and returns a new date.
java
LocalDate newDate = oldDate.plusDays(5);Example
This example shows how to get the current date, add 10 days to it, and print both dates.
java
import java.time.LocalDate; public class AddDaysExample { public static void main(String[] args) { LocalDate today = LocalDate.now(); LocalDate futureDate = today.plusDays(10); System.out.println("Today: " + today); System.out.println("Date after 10 days: " + futureDate); } }
Output
Today: 2024-06-15
Date after 10 days: 2024-06-25
Common Pitfalls
One common mistake is trying to modify the original LocalDate object directly. LocalDate is immutable, so methods like plusDays() return a new object and do not change the original.
Also, avoid using the old java.util.Date and Calendar classes for new code, as they are less clear and more error-prone.
java
/* Wrong way: This does NOT change the original date */ LocalDate date = LocalDate.now(); date.plusDays(5); // result ignored, date stays the same /* Right way: Assign the result to a new variable or the same one */ date = date.plusDays(5);
Quick Reference
| Method | Description |
|---|---|
| LocalDate.now() | Gets the current date. |
| plusDays(long days) | Returns a new date with days added. |
| minusDays(long days) | Returns a new date with days subtracted. |
| LocalDate.of(year, month, day) | Creates a date with specific year, month, and day. |
Key Takeaways
Use LocalDate.plusDays() to add days and get a new date object.
LocalDate is immutable; always use the returned value from plusDays().
Avoid old Date and Calendar classes for date arithmetic in modern Java.
LocalDate.now() gives the current date without time.
Use LocalDate.of() to create specific dates before adding days.