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


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


ofStrict()用於創建ZonedDateTime實例的ZonedDateTime類的方法,嚴格驗證本地日期時間,偏移量和區域ID的組合,其中所有三個Local date-tme,ZoneOffset和ZoneId均作為參數傳遞。如果偏移量無效,則引發異常。
用法:

public static ZonedDateTime ofStrict(LocalDateTime localDateTime,
                                     ZoneOffset offset,
                                     ZoneId zone)

參數:此方法接受三個參數localDateTime(是本地日期時間),offset(是區域偏移量)和zone(是時區)。

返回值:此方法返回分區的日期時間。


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

// Java program to demonstrate 
// ZonedDateTime.ofStrict() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create local date time object 
        LocalDateTime ldt 
            = LocalDateTime 
                  .parse("2019-01-29T23:55:59.00"); 
  
        // create ZoneOffset 
        ZoneOffset zoneOffset 
            = ZoneOffset.ofHours(1); 
  
        // create a ZonID 
        ZoneId zone 
            = ZoneId.of("Europe/Paris"); 
  
        // apply ofStrict method 
        // of ZonedDateTime class 
        ZonedDateTime zt 
            = ZonedDateTime 
                  .ofStrict( 
                      ldt, zoneOffset, zone); 
  
        // print the result 
        System.out.println("ZonedDateTime is "
                           + zt); 
    } 
}
輸出:
ZonedDateTime is 2019-01-29T23:55:59+01:00[Europe/Paris]

示例2:

// Java program to demonstrate 
// ZonedDateTime.ofStrict() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create local date-time object 
        LocalDateTime ldt 
            = LocalDateTime 
                  .parse("2019-01-29T23:55:59.00"); 
  
        // create ZoneOffset 
        ZoneOffset zoneOffset 
            = ZoneOffset.ofHours(0); 
  
        // create a ZonID 
        ZoneId zone = ZoneId.of("UTC"); 
  
        // apply ofStrict method 
        // of ZonedDateTime class 
        ZonedDateTime zt 
            = ZonedDateTime 
                  .ofStrict( 
                      ldt, zoneOffset, zone); 
  
        // print the result 
        System.out.println("ZonedDateTime is "
                           + zt); 
    } 
}
輸出:
ZonedDateTime is 2019-01-29T23:55:59Z[UTC]

參考文獻:
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#ofStrict(java.time.LocalDateTime, java.time.ZoneOffset, java.time.ZoneId)



相關用法


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