Java中的 OffsetTime get() 方法及示例
Java中OffsetTime类的get()方法从此时获取指定字段的值作为int。
句法 :
public int get(TemporalField field)
参数:此方法接受一个参数字段,该字段指定要获取的字段,而不是 null。
返回值:它返回字段的值。
异常:该函数抛出三个异常,如下所述:
- UnsupportedTemporalTypeException :如果该字段不受支持或值的范围超过一个 int,则抛出该异常
- DateTimeException :如果无法获取该字段的值或该值超出该字段的有效值范围,则抛出该异常。
- ArithmeticException : 如果发生数值溢出则抛出
下面的程序说明了get()方法:
程序 1:
Java
// Java program to demonstrate the get() method
import java.time.OffsetTime;
import java.time.temporal.ChronoField;
public class GFG {
public static void main(String[] args)
{
// Parses the time
OffsetTime time = OffsetTime.parse("15:30:30+07:00");
// gets the time
System.out.println(time.get(ChronoField.CLOCK_HOUR_OF_DAY));
}
}
Java
// Java program to demonstrate the get() method
import java.time.OffsetTime;
import java.time.temporal.ChronoField;
public class GFG {
public static void main(String[] args)
{
try {
// Parses the time
OffsetTime time = OffsetTime.parse("25:30:30+01:00");
// gets the time
System.out.println(time.get(ChronoField.CLOCK_HOUR_OF_DAY));
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
15
方案二:
Java
// Java program to demonstrate the get() method
import java.time.OffsetTime;
import java.time.temporal.ChronoField;
public class GFG {
public static void main(String[] args)
{
try {
// Parses the time
OffsetTime time = OffsetTime.parse("25:30:30+01:00");
// gets the time
System.out.println(time.get(ChronoField.CLOCK_HOUR_OF_DAY));
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.time.format.DateTimeParseException: Text '25:30:30+01:00' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 25
参考:https: Java/time/OffsetTime.html#get-java.time.temporal.TemporalField-