在这篇博文中,我们将通过实例介绍Java.time.Period类。
周期类简介
在java8中使用日期和时间API时,有一个要求是找出两个日期之间的时间量,这是一个常见的要求。
周期的单位是年、月、日,时间的长短是以年为单位。它是基于值的类。所以两个Period的对象进行平等检查可能会产生不可预知的结果。
签名
public final class Period extends Object implements ChronoPeriod,
Serializable
Java.time.Period和Java.time.Duration之间的区别?
Period是基于日期的时间测量,它的测量单位是年、月和日 Duration是基于时间的时间测量,测量单位是小时、分钟、秒和纳秒 Period用于人类可读的日期测量,如年/月 Duration更适合基于机器的纳秒计算的时间测量。
寻找一个人的年龄就是Period的一个例子。
有很多关于Period的使用例子。
创建一个Period对象
Period对象可以使用创建方法来创建。
of(), ofMonths(), ofDays(), ofYears() 方法用于创建一个周期的实例。
Period ofYears = Period.ofYears(5);
System.out.println(ofYears.getYears());
Period ofMonths = Period.ofMonths(11);
System.out.println(ofMonths.getMonths());
Period ofDays = Period.ofDays(20);
System.out.println(ofDays.getDays());
Period ofWeeks = Period.ofWeeks(6);
System.out.println(ofWeeks.getDays());
Period periodInYearMonthsTDays = Period.of(5, 11, 25);
System.out.println("Total Period: " + periodInYearMonthsTDays);
输出是
5
11
20
42
Total Period: P5Y11M25D
minus() minusDays() minusMonths() minusYears() 是将特定单位减去当前日期。
plus() plusDays() plusMonths() plusYears() 是将特定单位加入当前日期。
LocalDate localDate = LocalDate.now();
System.out.println(localDate);
LocalDate add5Days = localDate.plus(Period.ofDays(5));
System.out.println("Add 5 days"+add5Days);
// date before one week
LocalDate oneweekbefore = localDate.minus(Period.ofWeeks(1));
System.out.println("substract one week "+oneweekbefore);
// Number of dates between two dates
Period period = Period.between(oneweekbefore, add5Days);
System.out.println("difference in days"+period.getDays());
System.out.println("difference in months "+period.getMonths());
输出是
2018-08-28
Add 5 days2018-09-02
substract one week 2018-08-21
difference in days12
difference in months 0
如何使用Period类来计算年/月/日的年龄?
Period类提供了各种方法
getYears()- 返回这个时期的年数
getMonths()- 返回这个时期的月数
getDays()- 返回这个时期的日数
LocalDate currentDate = LocalDate.now();
LocalDate birthday = LocalDate.of(1995, Month.JANUARY, 1);
Period period = Period.between(birthday, currentDate);
System.out.println("Age is " + period.getYears() + " years, " + period.getMonths() +
" months, and " +period.getDays() +
" days old");
输出是
Age is 23 years, 7 months, and 27 days old