I have very simple code which calculates difference between two times:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
public class JavaApplication8 {
private static final SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss.SSS");
public static void main(String[] args) throws InterruptedException {
Date start = GregorianCalendar.getInstance().getTime();
Thread.sleep(100);
Date end = GregorianCalendar.getInstance().getTime();
long diff = end.getTime() - start.getTime();
System.out.println(timeFormat.format(diff));
}
}
but it prints 01:00:00.100
instead of 00:00:00.100
, why?
Other way to solve this. Actually time diff that you having is not millisecs of current time. Its is just time diff, so make a simple division of that u can have hours:mins:secs. And its quite fast.
Date start = GregorianCalendar.getInstance().getTime();
Thread.sleep(100);
Date end = GregorianCalendar.getInstance().getTime();
long longVal = end.getTime() - start.getTime();
long hours = longVal / 3600000;
long mins = (longVal % 3600) / 60000;
long secs = longVal % 60000;
System.out.println(hours + " " + mins + " " + secs);
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