java 1.8中关于时间区间计算的几种办法与区别
/***
* period用来计算年月日之间具体时间的每一段的区间差,比如两个年月日之间相隔了 多少年月日
*/
private static void periodDemo() {
LocalDate today = LocalDate.now();
System.out.println("Today : " + today);
LocalDate birthDate = LocalDate.of(1993, Month.OCTOBER, 19);
System.out.println("BirthDate : " + birthDate);
Period p = Period.between(birthDate, today);
System.out.printf("年龄 : %d 年 %d 月 %d 日", Math.abs(p.getYears()), Math.abs(p.getMonths()), p.getDays());
}
/***
* 用来判断两个时间段之间相隔天,小时,秒,纳秒,不能传localDate因为 底层将年月日转成纳秒/毫秒计算,因为不支持该单位而产生异常
*/
private static void durationDemo() {
Instant inst1 = Instant.now();
System.out.println("Inst1 : " + inst1);
Instant inst2 = inst1.plus(Duration.ofSeconds(10));
System.out.println("Inst2 : " + inst2);
long l = Duration.between(LocalDate.now(), LocalDate.now()).toMinutes();
System.out.println(l);
System.out.println("Difference in milliseconds : " + Duration.between(inst1, inst2).toMillis());
System.out.println("Difference in seconds : " + Duration.between(inst1, inst2).getSeconds());
}
/***
* ChronoUnit 指定时间单位内测量一段时间差,但需要根据可用的时间单位计算,比如无法根据年月日计算相隔多少个小时,因为不支持该单位
*/
private static void chroDemo() {
LocalDate startDate = LocalDate.of(1993, Month.OCTOBER, 19);
System.out.println("开始时间 : " + startDate);
LocalDate endDate = LocalDate.of(2017, Month.JUNE, 16);
System.out.println("结束时间 : " + endDate);
long daysDiff = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("两天之间的差在天数 : " + daysDiff);
// 直接报错,因为不支持小数
long hoursDiff = ChronoUnit.HOURS.between(startDate, endDate);
System.out.println("两天之间的差在小时数 : " + hoursDiff);
}