How can I calculate a time difference in Java?

Java 8 has a cleaner solution – Instant and Duration

Example:

import java.time.Duration;
import java.time.Instant;
...
Instant start = Instant.now();
//your code
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");

Leave a Comment