How to convert Milliseconds to “X mins, x seconds” in Java?

后端 未结 27 2177
夕颜
夕颜 2020-11-22 03:59

I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current Syste

27条回答
  •  日久生厌
    2020-11-22 04:14

    Firstly, System.currentTimeMillis() and Instant.now() are not ideal for timing. They both report the wall-clock time, which the computer doesn't know precisely, and which can move erratically, including going backwards if for example the NTP daemon corrects the system time. If your timing happens on a single machine then you should instead use System.nanoTime().

    Secondly, from Java 8 onwards java.time.Duration is the best way to represent a duration:

    long start = System.nanoTime();
    // do things...
    long end = System.nanoTime();
    Duration duration = Duration.ofNanos(end - start);
    System.out.println(duration); // Prints "PT18M19.511627776S"
    System.out.printf("%d Hours %d Minutes %d Seconds%n",
            duration.toHours(), duration.toMinutes() % 60, duration.getSeconds() % 60);
    // prints "0 Hours 18 Minutes 19 Seconds"
    

提交回复
热议问题