Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the time difference between two events in Java?

Tags:

java

datetime

I want to calculate time difference in seconds between to time instants. For example, during execution of the program, I set the value of a variable and after some time I change it again. What was the time difference between the recent change of value from the previous value?

like image 709
Space Rocker Avatar asked Dec 25 '10 23:12

Space Rocker


People also ask

How do you find the time between two events?

To measure time between two events, you need to create a section in your project that will begin counting time at the start of the first event and continue counting until the second event stops the counter.

How can I get the difference between two dates in Java 8?

Using JodaTime, you can get the difference between two dates in Java using the following code: Days d = Days. daysBetween(startDate, endDate). getDays();

How do you add and subtract time in Java?

Add or Subtract Time – Java 7 We can use the cal. add(unit, amount) method for adding and subtracting time. If the amount was positive number then specified amount of specified unit of time is added to the calendar.

How do you add HH mm in Java?

SimpleDateFormat sdf = new SimpleDateFormat("dd:HH:mm:ss"); Date d0 = sdf. parse("00:00:00:00"); // ref Date d1 = sdf. parse("00:01:09:14"); Date d2 = sdf.


1 Answers

You can use System.currentTimeMillis() to save the current time at one millisecond resolution. Just save the time whenever the first event occurs (better use a long var to hold that value) and again when the 2nd event occurs. The difference divided by 1000 will give you time difference in seconds.

like image 62
yurib Avatar answered Oct 21 '22 06:10

yurib