1.Period
final修饰,线程安全,ISO-8601日历系统中基于日期的时间量,例如2年3个月4天。
主要属性:年数,月数,天数。
/** * 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个日期。
例如:
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());
输出:
years:0 months:1 days:17
2.Duration
final修饰,线程安全,基于时间的时间量,如“34.5秒”。
主要属性:秒,纳秒
/** * 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个时间。
例如:
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
Java日期时间API系列9-----Jdk8中java.time包中的新的日期时间API类的Period和Duration的区别
原文:https://www.cnblogs.com/xkzhangsanx/p/12110137.html