📜  Java中的 ZoneOffset ofHoursMinutesSeconds(int, int, int) 方法及示例

📅  最后修改于: 2022-05-13 01:54:54.842000             🧑  作者: Mango

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 实例的 int hours。它的范围是 +18 到 -18
  • minutes :这是要转换为 ZoneOffset 实例的 int 分钟数。它的范围是 -59 到 +59
  • seconds :这是要转换为 ZoneOffset 实例的 int 秒数。它的范围是 -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 文档