Search code examples
javastringtimejava-8localdate

Getting a time difference in Java LocalDateTime and converting it to String format


I'm taking a time difference between two LocalDateTime values. I'm using the Duration for that. And now I want to convert it into hh:mm:ss format as a String value. I've been checking how this can be done but still no luck. Any guidance will be appreciated.

 LocalDateTime startTime = some value
 LocalDateTime endTime = some value
 Duration totalWaitingDuration = Duration.between(endTime, startTime);
 String waitingTime = String.valueOf(totalWaitingDuration.toHours()); 

In this, I'm getting the time difference only in hours. How can i get it in hh:mm:ss format?


Solution

  • You can use apache commons:

    DurationFormatUtils.formatDuration(totalWaitingDuration.toMillis(), "H:mm:ss", true)
    

    Duration must not be negative.