java8计算时间差

时间:2022-09-05 22:07:59
示例1:计算指定时间单位的时间差

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

// LocalDateTime fromDate= LocalDateTime.now();
// LocalDateTime toDate= LocalDateTime.now();
Instant fromDate=Instant.now();
Instant toDate=Instant.now();
long minutes = ChronoUnit.MINUTES.between(fromDate, toDate);
long hours = ChronoUnit.HOURS.between(fromDate, toDate);

 注意:由于LocalDateTime和Instant是为不同的目的而设计的,一个是为了便于人阅读使用,另一个是为了便于机器处理,所以你不能将二者混用。

不能向between方法传递一个LocalDate对象做参数,否则会抛异常 java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit:

 

示例2:计算你的年龄

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1996, Month.JANUARY, 1);

Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);

System.out.println("你活了" + p.getYears() + "年" + p.getMonths() +
                "个月零" + p.getDays() +
                " 天(共" + p2 + "天)");
 
//输出:你活了22年11个月零18 天(共8388天)

参考文档:https://docs.oracle.com/javase/tutorial/datetime/iso/period.html