Java 8: Difference between two LocalDateTime in multiple units

后端 未结 10 1682
后悔当初
后悔当初 2020-11-22 11:36

I am trying to calculate the difference between two LocalDateTime.

The output needs to be of the format y years m months d days h hours m minutes

10条回答
  •  孤街浪徒
    2020-11-22 11:54

    Unfortunately, there doesn't seem to be a period class that spans time as well, so you might have to do the calculations on your own.

    Fortunately, the date and time classes have a lot of utility methods that simplify that to some degree. Here's a way to calculate the difference although not necessarily the fastest:

    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 + " years " + 
            months + " months " + 
            days + " days " +
            hours + " hours " +
            minutes + " minutes " +
            seconds + " seconds.");
    
    //prints: 29 years 8 months 24 days 22 hours 54 minutes 50 seconds.
    

    The basic idea is this: create a temporary start date and get the full years to the end. Then adjust that date by the number of years so that the start date is less then a year from the end. Repeat that for each time unit in descending order.

    Finally a disclaimer: I didn't take different timezones into account (both dates should be in the same timezone) and I also didn't test/check how daylight saving time or other changes in a calendar (like the timezone changes in Samoa) affect this calculation. So use with care.

提交回复
热议问题