當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java LocalTime truncatedTo()用法及代碼示例


LocalTime類的truncatedTo()方法用於以指定單位獲取此LocalTime的值。此方法采用參數Unit,這是該LocalTime被截斷為的單位。它返回帶有指定單位的值的截斷的不可變LocalTime。

用法:

public LocalTime truncatedTo(TemporalUnit unit)

參數:此方法接受單個參數uint,該參數uint表示要截斷的單位,不應為null。


返回值:此方法基於此時間返回不可變的,被截斷的LocalTime,該時間被截斷,而不是null。

異常:此方法引發以下兩個異常:

  • DateTimeException:如果無法截斷。
  • UnsupportedTemporalTypeException:如果不支持本機

以下示例程序旨在說明truncatedTo()方法:

程序1:

// Java program to demonstrate 
// LocalTime.truncatedTo() method 
  
import java.time.*; 
import java.time.temporal.ChronoUnit; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a LocalTime object 
        LocalTime time 
            = LocalTime.parse("21:45:36.13"); 
  
        // print instance 
        System.out.println("LocalTime before"
                           + " truncate: "
                           + time); 
  
        // truncate to ChronoUnit.MINUTES 
        // means unit smaller than Minute 
        // will be Zero 
        LocalTime returnvalue 
            = time.truncatedTo(ChronoUnit.MINUTES); 
  
        // print result 
        System.out.println("LocalTime after "
                           + " truncate: "
                           + returnvalue); 
    } 
}
輸出:
LocalTime before truncate: 21:45:36.130
LocalTime after  truncate: 21:45

程序2:

// Java program to demonstrate 
// LocalTime.truncatedTo() method 
  
import java.time.*; 
import java.time.temporal.ChronoUnit; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a LocalTime object 
        LocalTime time 
            = LocalTime.parse("01:21:30.13"); 
  
        // print instance 
        System.out.println("LocalTime before"
                           + " truncate: "
                           + time); 
  
        // truncate to ChronoUnit.HOURS 
        // means unit smaller than Hour 
        // will be Zero 
        LocalTime returnvalue 
            = time.truncatedTo(ChronoUnit.HOURS); 
  
        // print result 
        System.out.println("LocalTime after "
                           + " truncate: "
                           + returnvalue); 
    } 
}
輸出:
LocalTime before truncate: 01:21:30.130
LocalTime after  truncate: 01:00

參考: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#truncatedTo(java.time.temporal.TemporalUnit)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 LocalTime truncatedTo() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。