Java MonthDay getLong()方法及示例

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

Java MonthDay getLong()方法及示例

Java中 MonthDay类getLong() 方法从这个月日中获取指定字段的值作为一个长条。

语法

public long getLong(TemporalField field)

参数: 该方法接受一个参数 字段 ,该字段指定getLong的字段,并且不为空。
返回 :该函数返回该字段的 长值
异常 :该函数抛出三个异常,如下所述。

DateTimeException :当不能获得字段的值或该值超出该字段的有效值范围时,会抛出这个异常。UnsupportedTemporalTypeException :当字段不被支持或者数值范围超过了一个长的值时,就会抛出这个异常。ArithmeticException :当发生数字溢出时抛出。

以下程序说明了 MonthDay.getLong() 方法:

程序1 :

// Program to illustrate the getLong() method import java.util.*;import java.time.*;import java.time.temporal.ChronoField; public class GfG {    public static void main(String[] args)    {         // Parses the date        MonthDay tm1 = MonthDay.parse("--10-12");         System.out.println(            tm1.getLong(ChronoField.DAY_OF_MONTH));    }}

输出

12

程序2

// Program to illustrate the getLong() method import java.util.*;import java.time.*;import java.time.temporal.ChronoField; public class GfG {    public static void main(String[] args)    {         // Parses the date        MonthDay tm1            = MonthDay.parse("--12-06");        System.out.println(            tm1.getLong(                ChronoField.DAY_OF_MONTH));    }}

输出

6

程序3: 演示DateTimeParseException

// Program to illustrate the getLong() method import java.util.*;import java.time.*;import java.time.temporal.ChronoField; public class GfG {    public static void main(String[] args)    {         try {             // Parses the date            MonthDay tm1                = MonthDay.parse("--13-12");             System.out.println(                tm1.getLong(                    ChronoField.DAY_OF_MONTH));        }        catch (Exception e) {            System.out.println(e);        }    }}

输出

java.time.format.DateTimeParseException: Text '--13-12' could not be parsed: Unable to obtain MonthDay from TemporalAccessor: {DayOfMonth=12, MonthOfYear=13}, ISO of type java.time.format.Parsed

参考资料: https://docs.oracle.com/javase/8/docs/api/java/time/MonthDay.html#getLong-java.time.temporal.TemporalField-

相关推荐