addMinutes()
is a DateUtils
utility which is used to add a given number of minutes to the Date
object and return a new Date
object. 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 addMinutes(final Date date, final int amount)
final Date date
: The date to add.final int amount
: The number of minutes to add. Can be positive or negative.This method returns a new Date
with the number of minutes added.
In the code below, we will store the number of minutes in the minutesToAdd
variable and add to the currDate
object with the help of the addMinutes()
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 minutesToAdd = 30;Date newDate = DateUtils.addMinutes(currDate, minutesToAdd);System.out.printf("%s + %s minutes = %s", currDate, minutesToAdd, newDate);}}
The output of the code will be as follows:
Sun Nov 21 03:13:02 IST 2021 + 30 minutes = Sun Nov 21 03:43:02 IST 2021
Free Resources