Java MonthDay get()方法及示例
Java中 MonthDay类 的 get() 方法从这个月日的指定字段中获取一个int的值。
语法
public int get(TemporalField field)
参数: 该方法接受一个参数 字段 ,指定要获取的字段,并且不为空。
返回: 该函数返回字段的值。
异常 :该函数抛出三种异常,描述如下。
DateTimeException :当不能获得字段的值或该值超出该字段的有效值范围时,会抛出这个异常。UnsupportedTemporalTypeException :当字段不被支持或值的范围超过一个int时,就会抛出该异常。ArithmeticException :当发生数字溢出时抛出。以下程序说明了 MonthDay.get() 方法:
程序1 :
// Program to illustrate the get() 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.get(ChronoField.DAY_OF_MONTH)); }}
输出
12
程序2
// Program to illustrate the get() 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.get(ChronoField.DAY_OF_MONTH)); }}输出
6
程序3: 演示DateTimeParseException
// Program to illustrate the get() 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.get(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#get-java.time.temporal.TemporalField-
