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


Java ZoneOffset ofHoursMinutesSeconds(int, int, int)用法及代碼示例


java.time包中的ZoneOffset類的ofHoursMinutesSeconds(int,int,int)方法使用以小時,分鍾和秒為單位的偏移量作為參數來獲取ZoneOffset的實例。此方法將小時,分鍾和秒作為參數(以int的形式)並將其轉換為ZoneOffset。

用法:

public static ZoneOffset
  ofHoursMinutesSeconds(int hours, 
                        int minutes,  
                        int seconds)

參數:此方法接受3個參數:


  • hours:要轉換為ZoneOffset實例的整數小時。範圍是+18至-18
  • minutes:要轉換為ZoneOffset實例的整數分鍾。其範圍是-59至+59
  • seconds:要轉換為ZoneOffset實例的整數秒。其範圍是-59至+59

返回值:此方法返回從指定的小時,分​​鍾和秒開始解析的ZoneOffset實例。

異常:如果小時,分鍾和秒無效,則此方法將引發DateTimeException。

以下示例說明了ZoneOffset.ofHoursMinutesSeconds()方法:

範例1:

// Java code to illustrate ofHoursMinutesSeconds() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the hours, minutes and seconds 
        int hours = 5; 
        int minutes = 20; 
        int seconds = 50; 
  
        // ZoneOffset using ofHoursMinutesSeconds() method 
        ZoneOffset zoneOffset 
            = ZoneOffset 
                  .ofHoursMinutesSeconds(hours, 
                                         minutes, 
                                         seconds); 
  
        System.out.println(zoneOffset); 
    } 
}
輸出:
+05:20:50

範例2:演示DateTimeException

// Java code to illustrate ofHoursMinutesSeconds() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the invalid hours, minutes and seconds 
        int hours = 20; 
        int minutes = 5; 
        int seconds = 0; 
  
        try { 
            // ZoneOffset using ofHoursMinutesSeconds() method 
            ZoneOffset zoneOffset 
                = ZoneOffset 
                      .ofHoursMinutesSeconds(hours, 
                                             minutes, 
                                             seconds); 
        } 
  
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
java.time.DateTimeException:
 Zone offset hours not in valid range:
 value 20 is not in the range -18 to 18

參考: Oracle Doc



相關用法


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