Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time difference - strange result

Tags:

java

date

time

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?

like image 896
tobi Avatar asked Dec 12 '22 12:12

tobi


1 Answers

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);
like image 57
Selvaraj Avatar answered Dec 14 '22 02:12

Selvaraj