Period :表示一段时间的区间,用来度量 年、月、日和几天 之间的时间值。
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) {}
public int getYears() {}
public int getMonths() {}
public int getDays() {}
public long toTotalMonths() {}
public static Duration between(Temporal startInclusive, Temporal endExclusive) {}
public long toDays() {}
public long toHours() {}
public long toMinutes() {}
public long toMillis() {}
public long toNanos() {}
package com.github.date.jdk8.demo11;
import java.time.LocalDate;
import java.time.Period;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class Test {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println("now = " + now); // now = 2021-09-27
LocalDate future = LocalDate.now().plusYears(1).plusDays(1).plusMonths(1);
System.out.println("future = " + future); // future = 2022-10-28
Period period = Period.between(now, future);
int years = period.getYears();
System.out.println("区间相差的年 = " + years); // 区间相差的年 = 1,其实就是 future 的year - now的year
int months = period.getMonths();
System.out.println("区间相差的月 = " + months); // 区间相差的月 = 1,其实就是 future 的month - now的month
int days = period.getDays();
System.out.println("区间相差的天 = " + days); // 区间相差的天 = 1,其实就是 future 的day - now的day
long totalMonths = period.toTotalMonths();
System.out.println("区间相差几个月 = " + totalMonths); // 区间相差几个月 = 13,实际相差的月
}
}
示例:
package com.github.date.jdk8.demo12;
import java.time.Duration;
import java.time.LocalDateTime;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class Test {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now); // now = 2021-09-27T13:29:56.105
LocalDateTime feture = LocalDateTime.now().plusYears(1).plusMonths(1).plusDays(1).plusHours(1).plusMonths(1)
.plusSeconds(1).plusNanos(1);
System.out.println("feture = " + feture); // feture = 2022-11-28T14:29:57.106000001
Duration duration = Duration.between(now, feture);
long seconds = duration.getSeconds();
System.out.println("seconds = " + seconds); // seconds = 36896401
int nano = duration.getNano();
System.out.println("nano = " + nano); // nano = 1000001
}
}