使用java.time包中ZoneOffset类的ofHours(int)方法,以传递的小时数偏移量作为参数来获取ZoneOffset的实例。此方法将小时数作为int形式的参数并将其转换为ZoneOffset。支持的最大范围是从+18:00到-18:00(含)。
用法:
public static ZoneOffset ofHours(int hours)
参数:此方法接受参数hours,该参数的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