Tuesday, October 7, 2025
HomeLanguagesJavaLocalDateTime withHour() method in Java with Examples

LocalDateTime withHour() method in Java with Examples

The withHour() method of LocalDateTime class in Java is used to get a copy of this LocalDateTime with the hours changed to the hours passed as the parameter to this method. The remaining values of this LocalDateTime remains the same.

Syntax:

public LocalDateTime withHour(int hours)

Parameter: This method accepts a single mandatory parameter hours which specifies the hours to be set in the resultant LocalDateTime instance. The value of this hours can range from 0 to 23.

Returns: The function returns a LocalDateTime instance with the hours changed to the hours passed as the parameter to this method. The remaining values of this LocalDateTime remains the same.

Exceptions: The function throws a DateTimeException if the hours value is invalid.

Below programs illustrate the LocalDateTime.withHour() method:

Program 1:




// Program to illustrate the withHour() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Get the LocalDateTime instance
        LocalDateTime dt = LocalDateTime.now();
  
        // Get the String representation of this LocalDateTime
        System.out.println("Original LocalDateTime: "
                           + dt.toString());
  
        // Get a new LocalDateTime with hours 0
        System.out.println("New LocalDateTime: "
                           + dt.withHour(0));
    }
}


Output:

Original LocalDateTime: 2018-11-30T12:53:06.591
New LocalDateTime: 2018-11-30T00:53:06.591

Program 2:




// Program to illustrate the withHour() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Get the LocalDateTime instance
        LocalDateTime dt
            = LocalDateTime
                  .parse("2015-04-06T10:15:30");
  
        // Get the String representation of this LocalDateTime
        System.out.println("Original LocalDateTime: "
                           + dt.toString());
  
        // Get a new LocalDateTime with hours 20
        System.out.println("New LocalDateTime: "
                           + dt.withHour(20));
    }
}


Output:

Original LocalDateTime: 2015-04-06T10:15:30
New LocalDateTime: 2015-04-06T20:15:30

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

RELATED ARTICLES

Most Popular

Dominic
32339 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6708 POSTS0 COMMENTS
Nicole Veronica
11872 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6827 POSTS0 COMMENTS
Ted Musemwa
7090 POSTS0 COMMENTS
Thapelo Manthata
6780 POSTS0 COMMENTS
Umr Jansen
6784 POSTS0 COMMENTS