import java.time.LocalDate; import java.time.Period; /* Period计算日期间隔 (年月日) */ public class PeriodDemo { public static void main(String[] args) { //此刻年月日 LocalDate today = LocalDate.now(); System.out.println(today); //昨天年月日 LocalDate otherDate = LocalDate.of(2024, 8, 22); System.out.println(otherDate); //Period对象表示时间的间隔对象 Period period = Period.between(today, otherDate); //第二个参数减第一个参数 System.out.println(period.getYears()); //间隔多少年 System.out.println(period.getMonths()); //间隔多少月 System.out.println(period.getDays()); //间隔多少天 System.out.println(period.toTotalMonths()); //总月份 } } 输出如下: 2024-07-23 2024-08-22 0 0 30 0
package code.interval; /* Duration计算日期间隔 (时分秒) */ public class DurationDemo { public static void main(String[] args) { } }
package code.interval; /* ChronoUnit可用于在单个时间单位内测量一段时间, 这个工具类较为全面, 可用于比较所有的时间单位 */ public class ChronoUnitDemo { public static void main(String[] args) { } }