setMinutes()
is a DateUtils
which sets the minutes field of the Date
object returning 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 setMinutes(Date date, int amount)
Date date
: The original Date
object.int amount
: The new value of minutes to set.This method returns a new Date
object with the minutes’ field set to the specified value.
import org.apache.commons.lang3.time.DateUtils;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;public class Main{public static void main(String[] args) {Date date = new Date();DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SS");int newMinuteValue = 5;Date newDate = DateUtils.setMinutes(date, newMinuteValue);System.out.printf("DateUtils.setMinutes(%s, %s) = %s", dateFormat.format(date), newMinuteValue, dateFormat.format(newDate));}}
Main
class.main()
function.Date
object.SimpleDateFormat
object with the format in which we want the dates to be printed.setMinutes()
method to set the minutes field of the date object defined in line 10.The output of the code will be as follows:
DateUtils.setMinutes(21/11/2021 14:17:11:37, 5) = 21/11/2021 14:05:11:37