What is DateUtils.addHours() in Java?

addHours() is a staticthe methods in Java that can be called without creating an object of the class. method of the DateUtils class that is used to add a given number of hours to the Date object and return 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>

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

Parameters

  • date: The date to add to.
  • amount: The number of hours to add. Can be positive or negative.

Return value

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

Code

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

Output

The output of the code will be as follows:

Sun Nov 21 03:21:49 IST 2021 + 1 hours = Sun Nov 21 04:21:49 IST 2021

Free Resources