📅  最后修改于: 2020-10-01 06:38:12             🧑  作者: Mango
Java Period类用于以年,月和日为单位来度量时间。它继承了Object类并实现了ChronoPeriod接口。
让我们来看一下java.time.Period类的声明。
public final class Period extends Object implements ChronoPeriod, Serializable
Method | Description |
---|---|
Temporal addTo(Temporal temporal) | It is used to add this period to the specified temporal object. |
long get(TemporalUnit unit) | It is used to get the value of the requested unit. |
int getYears() | It is used to get the amount of years of this period. |
boolean isZero() | It is used to check if all three units of this period are zero. |
Period minus(TemporalAmount amountToSubtract) | It is used to return a copy of this period with the specified period subtracted. |
static Period of(int years, int months, int days) | It is used to obtain a Period representing a number of years, months and days. |
Period plus(TemporalAmount amountToAdd) | It is used to return a copy of this period with the specified period added. |
import java.time.*;
import java.time.temporal.Temporal;
public class PeriodExample1 {
public static void main(String[] args) {
Period period = Period.ofDays(24);
Temporal temp = period.addTo(LocalDate.now());
System.out.println(temp);
}
}
输出:
2017-02-24
import java.time.Period;
public class PeriodExample2 {
public static void main(String[] args) {
Period period = Period.of(2017,02,16);
System.out.println(period.toString());
}
}
输出:
P2017Y2M16D
import java.time.Period;
public class PeriodExample3 {
public static void main(String[] args) {
Period period1 = Period.ofMonths(4);
Period period2 = period1.minus(Period.ofMonths(2));
System.out.println(period2);
}
}
输出:
P2M
import java.time.Period;
public class PeriodExample4 {
public static void main(String[] args) {
Period period1 = Period.ofMonths(4);
Period period2 = period1.plus(Period.ofMonths(2));
System.out.println(period2);
}
}
输出:
P6M