LocalTime類的withHour()方法用於獲取此LocalTime的副本,並將小時數更改為作為此方法的參數傳遞的小時數。此LocalTime的其餘值將保持不變。此實例是不可變的,不受此方法調用的影響。
用法:
public LocalTime withHour(int hour)
參數:此方法接受單個參數小時,該小時代表要在結果中設置的hour-of-day,範圍為0到23。
返回值:此方法基於此時間和所請求的小時返回LocalTime實例。
異常:如果小時值無效,則此方法引發異常DateTimeException
以下示例程序旨在說明withHour()方法:
示例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);
}
}
輸出:
Old LocalTime: 19:34:50.630 New LocalDateTime: 04:34:50.630
示例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);
}
}
輸出:
Old LocalTime: 01:21:30.130 New LocalDateTime: 23:21:30.130
參考文獻: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#withHour(int)
相關用法
- Java LocalDateTime withHour()用法及代碼示例
- Java OffsetDateTime withHour()用法及代碼示例
- Java ZonedDateTime withHour()用法及代碼示例
- Java LocalTime with()用法及代碼示例
- Java LocalTime until()用法及代碼示例
- Java LocalTime plus()用法及代碼示例
- Java LocalTime from()用法及代碼示例
- Java LocalTime get()用法及代碼示例
- Java LocalTime getLong()用法及代碼示例
- Java LocalTime format()用法及代碼示例
- Java LocalTime ofSecondOfDay()用法及代碼示例
- Java LocalTime equals()用法及代碼示例
- Java LocalTime isSupported()用法及代碼示例
- Java LocalTime compareTo()用法及代碼示例
- Java LocalTime isAfter()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 LocalTime withHour() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。