Home > Java > javaTutorial > How Can I Accurately Measure the Duration Between Two Time Points in Java, Even When the Start Time is After the End Time?

How Can I Accurately Measure the Duration Between Two Time Points in Java, Even When the Start Time is After the End Time?

Mary-Kate Olsen
Release: 2024-12-20 14:30:09
Original
631 people have browsed it

How Can I Accurately Measure the Duration Between Two Time Points in Java, Even When the Start Time is After the End Time?

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;
    }

    // ...
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template