Java Instant get()方法及实例

来源:这里教程网 时间:2026-02-17 20:51:52 作者:

Java Instant get()方法及实例

Instant类get() 方法有助于从这个瞬间获得作为参数传递的指定字段的整数值。这个方法查询这个瞬间的字段值,返回的值总是在该字段的有效范围内。当该字段不被支持,并且该方法无法返回int值时,就会产生一个异常。

语法

public int get(TemporalField field)

参数: 该方法接受一个参数 字段 ,即要获取的字段。

返回: 该方法返回字段的 int 值。

异常: 该方法会抛出以下异常。

DateTimeException :如果不能获得该字段的值,或者该值超出该字段的有效值范围。UnsupportedTemporalTypeException : 如果该字段不被支持或者数值范围超过了一个int。ArithmeticException :如果发生数字溢出。

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

程序1 :

// Java program to demonstrate// Instant.get() method import java.time.*;import java.time.temporal.ChronoField; public class GFG {    public static void main(String[] args)    {         // create a Instant object        Instant instant            = Instant.parse("2018-12-30T19:34:50.63Z");         // get Milli of Second value from instant        // using get method        int secondvalue            = instant.get(ChronoField.MILLI_OF_SECOND);         // print result        System.out.println("MilliSecond Field: "                           + secondvalue);    }}

输出

MilliSecond Field: 630

程序2

// Java program to demonstrate// Instant.get() method import java.time.*;import java.time.temporal.ChronoField; public class GFG {    public static void main(String[] args)    {         // create a Instant object        Instant instant            = Instant.parse("2018-12-30T01:34:50.93Z");         // get Nano of Second value from instant        // using get method        int secondvalue            = instant.get(ChronoField.NANO_OF_SECOND);         // print result        System.out.println("Nano of Second: "                           + secondvalue);    }}

输出

Nano of Second: 930000000

程序3: 获取UnsupportedTemporalTypeException

// Java program to demonstrate// Instant.get() method import java.time.*;import java.time.temporal.ChronoField; public class GFG {    public static void main(String[] args)    {         // create a Instant object        Instant instant            = Instant.parse("2018-12-30T01:34:50.93Z");         // try to find era using ChronoField        try {             int secondvalue                = instant.get(ChronoField.ERA);        }        catch (Exception e) {             // print exception            System.out.println("Exception: " + e);        }    }}

输出

Exception: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Era

**References: ** https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#get(java.time.temporal.TemporalField)

相关推荐