Java Period get()方法及示例
Java中Period类的get()方法用于从这个Period中获取参数中给出的请求单位(年、月或日)的值。
语法
public long get(TemporalUnit unit)
参数: 该方法接受一个TemporalUnit类型的单参数单位,它是获得所需单位的单位。
返回值: 该函数返回所要求的单位的长值。
异常情况
DateTimeException – 如果参数中的单位不被支持,该方法会抛出DateTimeException。UnsupportedTemporalTypeException – 如果参数中的单位不被支持,该方法会抛出UnsupportedTemporalTypeException。下面的程序说明了上述方法。
程序1 :
// Java code to show the function get()// which gives the requested unitimport java.time.Period;import java.time.temporal.ChronoUnit; public class PeriodDemo { // Function to get requested unit static void getUnit(int year, int months, int days) { Period period = Period.of(year, months, days); System.out.println(period.get(ChronoUnit.DAYS)); } // Driver Code public static void main(String[] args) { int year = 8; int months = 5; int days = 25; getUnit(year, months, days); }}
输出:
25
程序2
// Java code to show the function get()// which gives the requested unitimport java.time.Period;import java.time.temporal.ChronoUnit; public class PeriodDemo { // Function to get requested unit static void getUnit(int year, int months, int days) { Period period = Period.of(year, months, days); System.out.println(period.get(ChronoUnit.YEARS)); } // Driver Code public static void main(String[] args) { int year = 11; int months = 3; int days = 21; getUnit(year, months, days); }}输出:
11
