What is DateUtils.setHours() in Java?
Overview
setHours() is a DateUtils used to set the hours field of 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>
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 setHours(final Date date, final int amount)
Parameters
final Date date: The originalDateobject.final int amount: The new value of hours to set.
Return value
This method returns a new Date object with the hours’ field set to the specified value.
Code
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 newHourValue = 5;Date newDate = DateUtils.setHours(date, newHourValue);System.out.printf("DateUtils.setHours(%s, %s) = %s", dateFormat.format(date), newHourValue, dateFormat.format(newDate));}}
Explanation
- From line 1 to line 5, we import the relevant packages.
- In line 7, we create
Mainclass. - In line 9, we make a
main()function. - In line 10, we create a
Dateobject. - In line 11, we create a
SimpleDateFormatobject with the format in which we want the dates to be printed. - In line 12, we define the new value of the hour field to set.
- In line 13, we use the
setHours()method to set the hours field of the date object defined in line 10. - In line 14, we print the original date, new hour value, and the new date object we obtained in line 13.
Output
The output of the code will be as follows:
DateUtils.setHours(21/11/2021 14:32:44:614, 5) = 21/11/2021 05:32:44:614
Free Resources
Attributions:
- undefined by undefined