可以使用Duration类计算两个LocalDateTime之间的时间差。示例如下:
LocalDateTime start = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
LocalDateTime end = LocalDateTime.of(2022, 1, 1, 0, 10, 0);
Duration duration = Duration.between(start, end);
System.out.println("时间差为:" + duration.getSeconds() + "秒");
注意:这个计算,只计算差值,没有正负数!
ChronoUnit类可以计算时间差的单位,可以指定计算到年、月、日、小时、分钟、秒等。示例如下:
LocalDateTime start = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
LocalDateTime end = LocalDateTime.of(2022, 1, 1, 0, 10, 0);
long seconds = ChronoUnit.SECONDS.between(start, end);
System.out.println("时间差为:" + seconds + "秒");
使用.until(方法:
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);
LocalDateTime还有很多方法