java.time.LocalDateTime.withHour() Method Example



Description

The java.time.LocalDateTime.withHour(int hour) method returns a copy of this LocalDateTime with the hour-of-day altered.

Declaration

Following is the declaration for java.time.LocalDateTime.withHour(int hour) method.

public LocalDateTime withHour(int hour)

Parameters

hour − the hour-of-day to set in the result, from 0 to 23.

Return Value

a LocalDateTime based on this date with the requested hour, not null.

Exceptions

DateTimeException − if the hour-of-day value is invalid.

Example

The following example shows the usage of java.time.LocalDateTime.withHour(int hour) method.

package com.tutorialspoint;

import java.time.LocalDateTime;

public class LocalDateTimeDemo {
   public static void main(String[] args) {
      
      LocalDateTime date = LocalDateTime.parse("2017-01-03T10:15:30");
      LocalDateTime result = date.withHour(3);
      System.out.println(result);  
   }
}

Let us compile and run the above program, this will produce the following result −

2017-01-03T03:15:30
Advertisements