Java OffsetDateTime get()方法及示例
Java中OffsetDateTime类的 get() 方法从这个日期中获取指定字段的值,作为一个int。
语法:
public int get(TemporalField field)
参数: 该方法接受一个单参数 字段 ,指定要获取的字段,而不是空字段。
返回值: 它返回字段的值。
异常 :该函数抛出三个异常:
DateTimeException :如果不能获得字段的值,或者该值超出了该字段的有效值范围,就会抛出这个异常。UnsupportedTemporalTypeException : 如果该字段不被支持或其值的范围超过了一个int,则抛出此异常。ArithmeticException : 如果发生数字溢出,就会抛出。下面的程序说明了 get()方法:
程序1 :
// Java program to demonstrate the get() method import java.time.OffsetDateTime;import java.time.temporal.ChronoField; public class GFG { public static void main(String[] args) { // Function used OffsetDateTime date = OffsetDateTime.parse("2017-02-03T12:30:30+01:00"); // Prints the date System.out.println(date.get(ChronoField.CLOCK_HOUR_OF_DAY)); }}
输出
12
程序2 :
// Java program to demonstrate the get() method// Exceptions import java.time.OffsetDateTime;import java.time.temporal.ChronoField; public class GFG { public static void main(String[] args) { try { // Function used OffsetDateTime date = OffsetDateTime.parse("2017-13-03T12:30:30+01:00"); // Prints the date System.out.println(date.get(ChronoField.CLOCK_HOUR_OF_DAY)); } catch (Exception e) { System.out.println(e); } }}输出
java.time.format.DateTimeParseException: Text '2017-13-03T12:30:30+01:00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13
参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#get-java.time.temporal.TemporalField-
