Measuring Time Elapsed in Java
Question:
How can I determine the duration between two time points in Java? Specifically, I want to represent startTime and endTime as instance variables in a class and calculate their difference in a getDuration() method. However, there's a constraint: I need to handle cases where startTime is later than endTime and still get an accurate result (e.g., startTime = 23:00, endTime = 1:00, duration = 2:00).
Answer:
To achieve accurate time measurement in Java, you must utilize System.nanoTime(). Contrary to System.currentTimeMillis(), nanoTime is designed specifically for measuring elapsed time.
Explanation:
System.currentTimeMillis() provides wall-clock time, which is susceptible to adjustments and corrections by the system. This leads to inconsistencies when measuring elapsed time. On the other hand, System.nanoTime() is unaffected by these corrections and offers precise measurement of time differences, even if startTime exceeds endTime.
To implement this in your class:
public class Stream { private long startTime; private long endTime; public long getDuration() { return endTime - startTime; } // ... }
By utilizing System.nanoTime(), you can obtain accurate time duration calculations, even when handling time intervals spanning across midnight or with startTime occurring after endTime.
The above is the detailed content of How Can I Accurately Measure the Duration Between Two Time Points in Java, Even When the Start Time is After the End Time?. For more information, please follow other related articles on the PHP Chinese website!