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?
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.
Using JodaTime, you can get the difference between two dates in Java using the following code: Days d = Days. daysBetween(startDate, endDate). getDays();
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With