Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
addmonths
dateutils

What is DateUtils.addMonths() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

addMonths() is a staticthe methods in Java that can be called without creating an object of the class. method of the DateUtils utility which is used to add a given number of months to the Date object, returning a new Date object.

The original date object remains unchanged.

How to import 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>
Importing the DateUtils

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 addMonths(final Date date, final int amount)

Parameters

  • final Date date: The date to add to.
  • final int amount: The number of months to add. Can be positive or negative.

Return value

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

Code

In the below code, we add the number of months in the monthsToAdd variable to the currDate object with the help of the addMonths() 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 monthsToAdd = 2;
Date newDate = DateUtils.addMonths(currDate, monthsToAdd);
System.out.printf("%s + %s months = %s", currDate, monthsToAdd, newDate);
}
}
Example of DateUtils.addMonths

Output

The output of the code will be as follows:


Sun Nov 21 03:29:58 IST 2021 + 2 months = Fri Jan 21 03:29:58 IST 2022

RELATED TAGS

java
communitycreator
addmonths
dateutils

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring