3

Is there any way to use the Instant class in Java to get elapsed time in seconds to a certain number of decimal points? I took some time to experiment, and I was able to to use the .now() method at two separate points in the program, and subtract them to get the elapsed time. However, my problem was I couldn't get the seconds to a specific number of decimal points.

2
  • 1
    What do you mean you "couldn't get the seconds to a specific number of decimal points"? What specific problem did you encounter?
    – Sweeper
    Commented Jul 10 at 6:13
  • 1
    So you want to represent an elapsed span of time as a fractional number of seconds? If so, edit your Question to say so more clearly. Commented Jul 10 at 6:20

2 Answers 2

4

If you have two Instant instances, you can find the duration between them in whatever chronological unit you choose.

For your specific use case, since the number of required decimal points is unspecified, it's probably easiest to get the number of nanoseconds (this gives you the highest precision), divide that number by 1e+9 (the number of nanoseconds in a second), and then round and/or format to however many decimals you need.

import static java.time.temporal.ChronoUnit.NANOS;
import java.time.Instant;

class Test {
    public static void main(String[] args) throws InterruptedException {
        Instant start = Instant.now();
        Thread.sleep(320);
        Instant end = Instant.now();
        
        long nanos = NANOS.between(start, end);
        double seconds = (double) nanos / 1e9;
        
        System.out.println(String.format("%,.4f seconds", seconds));
    }
}

This generates an output like the following:

0.3202 seconds
0
1

You can use truncatedTo.

 public static void main(String[] args) throws InterruptedException {
   Instant start = Instant.now().truncatedTo(ChronoUnit.SECONDS);
   // code being timed
   Instant end = Instant.now().truncatedTo(ChronoUnit.SECONDS);
   Duration duration = Duration.between(start, end);

You could also use Clock.tickSeconds(ZoneId):

 public static void main(String[] args) throws InterruptedException {
   Clock clock = Clock.tickSeconds(ZoneId.systemDefault());
   Instant start = Instant.now(clock);
   // code being timed
   Instant end = Instant.now(clock);
   Duration duration = Duration.between(start, end);

Not the answer you're looking for? Browse other questions tagged or ask your own question.