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


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


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

用法:

public ZonedDateTime truncatedTo(TemporalUnit unit)

參數:此方法接受一個單個參數uint,該單位參數是該ZonedDateTime將被截斷到的單位。它不能為空。


返回值:此方法返回一個不可變的截斷的ZonedDateTime,其值以指定單位為單位。

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

  • DateTimeException:如果無法截斷。
  • UnsupportedTemporalTypeException:如果不支持該設備。

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

程序1:

// Java program to demonstrate 
// ZonedDateTime.truncatedTo() method 
  
import java.time.*; 
import java.time.temporal.ChronoUnit; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a ZonedDateTime object 
        ZonedDateTime zonedDT 
            = ZonedDateTime 
                  .parse( 
                      "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); 
  
        // print ZonedDateTime 
        System.out.println("ZonedDateTime before"
                           + " truncate: "
                           + zonedDT); 
  
        // truncate to ChronoUnit.HOURS 
        // means unit smaller than Hour 
        // will be Zero 
        ZonedDateTime returnvalue 
            = zonedDT.truncatedTo(ChronoUnit.HOURS); 
  
        // print result 
        System.out.println("ZonedDateTime after "
                           + " truncate: "
                           + returnvalue); 
    } 
}
輸出:
ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after  truncate: 2018-12-06T19:00+05:30[Asia/Calcutta]

程序2:

// Java program to demonstrate 
// ZonedDateTime.truncatedTo() method 
  
import java.time.*; 
import java.time.temporal.ChronoUnit; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a ZonedDateTime object 
        ZonedDateTime zonedDT 
            = ZonedDateTime 
                  .parse( 
                      "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); 
  
        // print ZonedDateTime 
        System.out.println("ZonedDateTime before"
                           + " truncate: "
                           + zonedDT); 
  
        // truncate to ChronoUnit.DAYS 
        // means unit smaller than DAY 
        // will be Zero 
        ZonedDateTime returnvalue 
            = zonedDT.truncatedTo(ChronoUnit.DAYS); 
  
        // print result 
        System.out.println("ZonedDateTime after "
                           + " truncate: "
                           + returnvalue); 
    } 
}
輸出:
ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after  truncate: 2018-12-06T00:00+05:30[Asia/Calcutta]

參考: https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#withZoneSameInstant(java.time.ZoneId)



相關用法


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