What is the DateUtils.addYears() method in Java?

Overview

The addYears() is a staticThe methods in Java that can be called without creating an object of the class. method of DateUtilsused to add a given number of years to the Date object and return a new Date object. The original date object remains unchanged.

How to import DateUtils

The definition of the DateUtils can be found in the Apache Commons Lang package that 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;

Syntax


public static Date addYears(final Date date, final int amount)

Parameters

  • final Date date: The date to add to.
  • final int amount: The number of years to add, it can be positive or negative.

Return value

This method returns a new Date with the number of years added.

Code

In the code below, we add the number of years in the yearsToAdd variable to the currDate object with the help of the addYears() method and print the new 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 yearsToAdd = 1;
Date newDate = DateUtils.addYears(currDate, yearsToAdd);
System.out.printf("%s + %s years = %s", currDate, yearsToAdd, newDate);
}
}

Output

The output of the code will be:


Sun Nov 21 03:20:03 IST 2021 + 1 years = Mon Nov 21 03:20:03 IST 2022

Free Resources

Attributions:
  1. undefined by undefined