How to calculate time difference in java?

后端 未结 17 1523
醉酒成梦
醉酒成梦 2020-11-22 16:33

I want to subtract two timeperiods say 16:00:00 from 19:00:00. Is there any java function for this? The results can be in milliseconds, seconds, or minutes.

17条回答
  •  春和景丽
    2020-11-22 17:09

    Java 8 has a cleaner solution - Instant and Duration

    Example:

    import java.time.Duration;
    import java.time.Instant;
    ...
    Instant start = Instant.now();
    //your code
    Instant end = Instant.now();
    Duration timeElapsed = Duration.between(start, end);
    System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");
    

提交回复
热议问题