Javatpoint Logo
Javatpoint Logo

How to Add Hours to The Date Object in Java?

Java plusHours() function of the LocalDateTime class can be used to add hours to a time value. In this section we will going to learn how to add hours to the date object in Java

In addition to the current date, we will also add hours to something like a string of dates.

Using LocalDateTime Class

To obtain the localdatetime object if you have a date in a String, first, parse the string using the parse() method.

Use the plusHours() method for adding hours to it after that.

File name: AddHours.java

Output:

The date is : 2023-01-19T17:28:13.048909208
 The date after adding hours is : 2023-01-19T20:28:13.048909208

If we already have a localdatetime object, we can use the plusHours() function instead of the parse() method.

Syntax

The plusHours() function has the following signature.

Here h denotes hours.

Return Value: It does not return null, but rather a copy from LocalDateTime that has the requested number of hours added.

It only accepts one long type value as a parameter.

Exceptions: If the result is greater than the supported (either MIN or MAX) date range, a DateTimeException is thrown.

This method call has no bearing on the initial instance (LocalDateTime), which is immutable.

Adjusting the Time By an Hour

In this case, the current time and date were obtained using the static now() function of the LocalDateTime class.

In order to add hours to this date, we then utilized the plusHours() function.

In Java, the LocalDateTime class represents local date and time.

Year, month, day, hour, minute, second, and nanoseconds are all included in this class.

File name: AddHours.java

Output:

The date is : 2023-01-19T17:28:13.048909208
 The date after adding hours is : 2023-01-19T20:28:13.048909208

Subtraction of Hours in Date Object

Negative values can also be used with the plusHours() method. It will therefore subtract the hours first from the date if we passed a negative integer.

So, if we pass the negative value, we can claim that the hours are subtracted from the date rather than added. Check out the code example below.

FileName: SubtractHours.java

Output:

The date is : 2023-01-19T17:28:13.048909208
 The date after subtracting hours is : 2023-01-19T14:28:13.048909208






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA