What is DateUtils.addMilliseconds() in Java?

Overview

addMilliseconds() is a staticthe methods in Java that can be called without creating an object of the class. method of DateUtils, which is used to add a given number of milliseconds 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>

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

Parameters

  • final Date date: The date to add.
  • final int amount: The number of milliseconds to add. It can be positive or negative.

Return Value

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

Code

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

Output

The output of the code will be:


Sun Nov 21 03:24:17 IST 2021 + 1000 milliseconds = Sun Nov 21 03:24:18 IST 2021

Free Resources