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 {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {}
    }

    @Test
    public void durationToString() throws InterruptedException {
        var start = Instant.now();
        this.slow();
        var duration = Duration.between(start, Instant.now());
        var durationAsString = duration.toString();  //ISO-8601
        System.out.println(durationAsString);
    }
}

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.

Comments:

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