addDays()
is a DateUtils
class that is used to add a given number of days to the Date
object. It returns a new Date
object. However, the original Date
object remains unchanged.
DateUtils
The definition of DateUtils
can be found in the Apache Commons Lang
package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-lang
package, refer to the Maven Repository.
You can import the DateUtils
class as follows:
import org.apache.commons.lang3.time.DateUtils;
public static Date addDays(final Date date, final int amount)
final Date date
: The Date
object to which a number of days have to be added.final int amount
: The number of days to add to the Date
object. Can be positive or negative.This method returns a new Date
object with the number of days added.
In the code snippet below, we assign the number of days to add to the daysToAdd
variable. We then pass this variable to the addDays()
method along with the currDate
object in order to add the number of days to the currDate
object. Finally, we print the new Date
object to the console.
import org.apache.commons.lang3.time.DateUtils;import java.util.Date;public class Main{public static void main(String[] args) {Date currDate = new Date();int daysToAdd = 5;Date newDate = DateUtils.addDays(currDate, daysToAdd);System.out.printf("%s + %s days = %s", currDate, daysToAdd, newDate);}}
The output of the code will be as follows:
Sun Nov 21 03:04:22 IST 2021 + 5 days = Fri Nov 26 03:04:22 IST 2021
Free Resources