Java ZoneOffset ofHours(int)方法及示例
java.time包中ZoneOffset类的ofHours(int)方法用于获得ZoneOffset的一个实例,该实例使用了作为参数的小时偏移量。这个方法以int的形式接收小时数作为参数,并将其转换为ZoneOffset。支持的最大范围是从+18:00到-18:00(含)。
语法。
public static ZoneOffset ofHours(int hours)
参数。该方法接受一个参数hour,它是int,将被转换成ZoneOffset实例。
返回值。该方法返回一个从指定小时数中解析出来的ZoneOffset实例。
异常情况。如果小时数无效,该方法会抛出DateTimeException。
下面的例子说明了ZoneOffset.ofHours()方法。
例子1:
// Java code to illustrate ofHours() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// Get the hours
int hours = 10;
// ZoneOffset using ofHours() method
ZoneOffset zoneOffset
= ZoneOffset.ofHours(hours);
System.out.println(zoneOffset);
}
}
输出。
+10:00
例2:演示DateTimeException
// Java code to illustrate ofHours() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// Get the invalid hours
int hours = 20;
try {
// ZoneOffset using ofHours() method
ZoneOffset zoneOffset
= ZoneOffset.ofHours(hours);
}
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
极客教程