Javaexercise.com

Get Local Date Time With Altered Hours Of Day In Java 8?

To alter or update the hours of date-time in Java, you can use the withHours() method of the LocalDateTime class of Java 8.

This method returns a copy of the local date-time after altering the hours.

For example, if you have a date-time object "2022-03-17T12:13:59.774819476" and want to alter its hours with 05 then the new date-time object will be  "2022-03-17T05:13:59.774819476".

Let's understand with the running examples.

Change the Minutes of Current Date Time in Java

In the below code, we first get the current date time object by using the now() method and then update its hours by using the withHour() method.

/* 
 *  Code example to get local date time with the specified altered hours in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// Current date and time
		LocalDateTime date = LocalDateTime.now();

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get new datetime with altered hours
		LocalDateTime newDate = date.withHour(5);

		// Display new date
		System.out.println("New date : "+newDate);

	}
}

Output:

Date : 2022-03-17T12:13:59.774819476
New date : 2022-03-17T05:13:59.774819476
 

Now,  let's have a look at this method signature:

public LocalDateTime withHour(int hour)

Package Name: java.time;

Class Name: LocalDateTime

Return Value: It returns a copy of the local date-time object after altering the specified number of hours, not null.

Parameters: It takes a single primitive int type value(0 to 23).

Exceptions: It throws a DateTimeException if the hour value is invalid.

Version: Since 1.8

Let's see some more examples.

 

The valid value of the hour field is between 0 to 23. If you pass anything beyond this then the method throws an exception. See the below java code.

/* 
 *  Code example to get local date time with the specified hours in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// Current date and time
		LocalDateTime date = LocalDateTime.now();

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get new datetime with altered day
		LocalDateTime newDate = date.withHour(50); // invalid hours range 

		// Display new date
		System.out.println("New date : "+newDate);

	}
}

Output:

Date : 2022-03-17T12:19:25.359124999
Exception in thread "main" java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 - 23): 50

 

Single Line Solution - Final Shot

Use this code to get results in a single line of code. If you are a beginner, skip this code.

LocalDateTime.now().withHour(10)

This code will return a local date object after altering hours with the 5 from the current date. You just replace the value with your input and get the result instantly.