Java 8: Difference between two LocalDateTime in multiple units

后端 未结 10 1685
后悔当初
后悔当初 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:44

    Here a single example using Duration and TimeUnit to get 'hh:mm:ss' format.

    Duration dur = Duration.between(localDateTimeIni, localDateTimeEnd);
    long millis = dur.toMillis();
    
    String.format("%02d:%02d:%02d", 
            TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) - 
            TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
            TimeUnit.MILLISECONDS.toSeconds(millis) - 
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
    

提交回复
热议问题