Java中的 ChronoPeriod get() 方法及示例
Java中ChronoPeriod 接口的get()方法用于从该 ChronoPeriod 获取参数中给定的请求单位(YEARS、MONTHS 或 DAYS)的值。
句法:
long get(TemporalUnit unit)
参数:此方法接受 TemporalUnit 类型的单个参数单位,这是获取所需单位的单位。
返回值:此函数返回请求单位的长值。
例外:
- DateTimeException – 如果不支持参数中的单位,此方法将引发 DateTimeException。
- UnsupportedTemporalTypeException – 如果不支持参数中给出的单位,此方法将抛出 UnsupportedTemporalTypeException。
下面的程序说明了上述方法:
方案一:
// Java code to show the function get()
// which gives the requested unit
import java.time.*;
import java.time.chrono.*;
import java.time.temporal.ChronoUnit;
public class ChronoPeriodDemo {
// Function to get requested unit
static void getUnit(int year, int months, int days)
{
ChronoPeriod 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
方案二:
// Java code to show the function get()
// which gives the requested unit
import java.time.*;
import java.time.chrono.*;
import java.time.temporal.ChronoUnit;
public class ChronoPeriodDemo {
// Function to get requested unit
static void getUnit(int year, int months, int days)
{
ChronoPeriod 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
参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/chrono/ChronoChronoPeriod.html#get-java.time.temporal.TemporalUnit-