原则上应该适用Period来计算,因为他是专门为这种需求设计的。当时他只能计算到两个时间差的,年月日
传入参数Period.between(LocalDate,LocalDate)
这里是计算两个LocalDateTime时间差的方法。
@Test
public void test2()
{
LocalDateTime fromDateTime = LocalDateTime.of(1984, 12, 16, 7, 45, 55);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 40, 45);
LocalDateTime tempDateTime = LocalDateTime.from( fromDateTime );
long years = tempDateTime.until( toDateTime, ChronoUnit.YEARS);
tempDateTime = tempDateTime.plusYears( years );
long months = tempDateTime.until( toDateTime, ChronoUnit.MONTHS);
tempDateTime = tempDateTime.plusMonths( months );
long days = tempDateTime.until( toDateTime, ChronoUnit.DAYS);
tempDateTime = tempDateTime.plusDays( days );
long hours = tempDateTime.until( toDateTime, ChronoUnit.HOURS);
tempDateTime = tempDateTime.plusHours( hours );
long minutes = tempDateTime.until( toDateTime, ChronoUnit.MINUTES);
tempDateTime = tempDateTime.plusMinutes( minutes );
long seconds = tempDateTime.until( toDateTime, ChronoUnit.SECONDS);
System.out.println( years + " 天 " +
months + " 月 " +
days + " 天 " +
hours + " 时 " +
minutes + " 分 " +
seconds + " 秒.");
}
输出效果
转载自:https://stackoverflow.com/questions/25747499/java-8-calculate-difference-between-two-localdatetime