1. Use the Duration class to calculate the time difference
The time difference between two LocalDateTimes can be calculated using the Duration class. Examples are as follows:
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() + "秒");
Note: This calculation only calculates the difference, no positive or negative numbers!
2. Use the ChronoUnit class to calculate the time difference
The ChronoUnit class can calculate the unit of time difference, and can specify the calculation to year, month, day, hour, minute, second, etc. Examples are as follows:
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 + "秒");
3. Use the ChronoUnit class to calculate the time difference
Use .until(method:
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 also has many methods