Saturday, October 25, 2025
HomeLanguagesJavaLocalTime withHour() method in Java with Examples

LocalTime withHour() method in Java with Examples

The withHour() method of a LocalTime class is used to get a copy of this LocalTime with the hours changed to the hours passed as the parameter to this method. The remaining values of this LocalTime will remain the same. This instance is immutable and unaffected by this method call.

Syntax:

public LocalTime withHour(int hour)

Parameters: This method accepts a single parameter hour which represents the hour-of-day to set in the result, from 0 to 23.

Return value: This method returns a LocalTime instance based on this time with the requested hour.

Exception: This method throws a exception DateTimeException if the hour value is invalid

Below programs illustrate the withHour() method:

Program 1:




// Java program to demonstrate
// LocalTime.withHour() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a LocalTime object
        LocalTime time
            = LocalTime.parse("19:34:50.63");
  
        // print time
        System.out.println("Old LocalTime: "
                           + time);
  
        // Get a new LocalDateTime with hours 4
        LocalTime newtime = time.withHour(4);
  
        // print result
        System.out.println("New LocalDateTime: "
                           + newtime);
    }
}


Output:

Old LocalTime: 19:34:50.630
New LocalDateTime: 04:34:50.630

Program 2:




// Java program to demonstrate
// LocalTime.withHour() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a LocalTime object
        LocalTime time
            = LocalTime.parse("01:21:30.13");
  
        // print time
        System.out.println("Old LocalTime: "
                           + time);
  
        // Get a new LocalDateTime with hours 23
        LocalTime newtime = time.withHour(23);
  
        // print result
        System.out.println("New LocalDateTime: "
                           + newtime);
    }
}


Output:

Old LocalTime: 01:21:30.130
New LocalDateTime: 23:21:30.130

References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#withHour(int)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS