final修饰,线程安全,ISO-8601日历系统中基于日期的时间量,例如2年3个月4天。express
主要属性:年数,月数,天数。安全
/** * The number of years. */ private final int years; /** * The number of months. */ private final int months; /** * The number of days. */ private final int days;
用于时间量,比较2个日期。spa
例如:线程
LocalDate localDate1 = LocalDate.of(2019, 11, 15); LocalDate localDate2 = LocalDate.of(2020, 1, 1); Period p = Period.between(localDate1, localDate2); System.out.println("years:"+p.getYears()+" months:"+p.getMonths()+" days:"+p.getDays());
输出:code
years:0 months:1 days:17blog
final修饰,线程安全,基于时间的时间量,如“34.5秒”。接口
主要属性:秒,纳秒get
/** * The number of seconds in the duration. */ private final long seconds; /** * The number of nanoseconds in the duration, expressed as a fraction of the * number of seconds. This is always positive, and never exceeds 999,999,999. */ private final int nanos;
用于时间量,比较2个时间。it
例如:io
LocalDateTime localDateTime1 = LocalDateTime.of(2019, 11, 15, 0, 0); LocalDateTime localDateTime2 = LocalDateTime.of(2019, 11, 15, 10, 30); Duration d = Duration.between(localDateTime1, localDateTime2); System.out.println("days:"+d.toDays()); System.out.println("hours:"+d.toHours()); System.out.println("minutes:"+d.toMinutes()); System.out.println("millis:"+d.toMillis());
输出:
days:0
hours:10
minutes:630
millis:37800000
Period包含年数,月数,天数,而Duration只包含秒,纳秒。
Period只能返回年数,月数,天数;Duration能够返回天数,小时数,分钟数,毫秒数等。
Period只能使用LocalDate,Duration能够使用全部包含了time部分且实现了Temporal接口的类,好比LocalDateTime,LocalTime和Instant等。
Period:
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
Duration:
public static Duration between(Temporal startInclusive, Temporal endExclusive)
经过上面的实例能够看出:
Period p.getDays() 获取天数时,只会获取days属性值,而不会将年月部分都计算整天数,不会有2020.1.1和2019.1.1比较后获取天数为365天的状况。
public int getDays() { return days; }
Duration d.toDays() 获取天数时,会将秒属性转换整天数。
public long toDays() { return seconds / SECONDS_PER_DAY; }
因此,想要获取2个时间的相差总天数,只能用Duration。
Period有获取总月数的方法:
public long toTotalMonths() { return years * 12L + months; // no overflow }
为何没有获取总天数方法?
由于between后获取到的Period,不会记录2个日期中间的闰年信息,有闰年的存在,每一年的天数不必定是365天,因此计算不许确。