Time Measurement with Duration, Instant, and ISO-8601

Duration is a viable alternative to System.currentTimeMillis() for time measurements (also checkout: Beyond System.currentTimeMillis: Measuring Time with Duration and Instant):

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;

public class DurationToStringTest {

    void slow(){
        try {
        } catch (InterruptedException e) {}

    public void durationToString() throws InterruptedException {
        var start = Instant.now();
        var duration = Duration.between(start, Instant.now());
        var durationAsString = duration.toString();  //ISO-8601

The method Duration#toString returns a combined representation of hours, minutes, seconds and fractional seconds, standardized by ISO-8601.

The above example produces the following output: PT1.001087S.


Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments