📌  相关文章
📜  Java中的 OffsetDateTime get() 方法及示例

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

Java中的 OffsetDateTime get() 方法及示例

Java中 OffsetDateTime 类的get()方法从该日期获取指定字段的值作为 int。

句法 :

public int get(TemporalField field)

参数:此方法接受单个参数字段,该字段指定要获取的字段,而不是 null。
返回值:它返回字段的值。
Exceptions :该函数throws 抛出三个异常:

  • DateTimeException :如果无法获取该字段的值或该值超出该字段的有效值范围,则抛出该异常。
  • UnsupportedTemporalTypeException :如果该字段不受支持或值的范围超过一个 int,则抛出该异常
  • ArithmeticException : 如果发生数值溢出则抛出

下面的程序说明了get()方法:
程序 1:

Java
// 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));
    }
}


Java
// 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);
        }
    }
}


输出:
12

方案二

Java

// 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: Java/time/OffsetDateTime.html#get-java.time.temporal.TemporalField-