当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。