Mahender Mahender - 6 months ago 27
Java Question

Displaying wrong time difference

I tried many ways to display the difference between two times, but I am unable to find a solution:

long strt = System.currentTimeMillis();//1462968291733
Thread.sleep(5000);
long end = System.currentTimeMillis();//1462968296733

long diff = end - strt;

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(diff);
TimeZone timeZone = TimeZone.getTimeZone("IST");
calendar.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));

System.out.println(calendar.getTime());//05:30:05


It is printing wrong output:


Thu Jan 01 05:30:05 IST 1970


The output should be


Thu Jan 01 00:00:05 IST 1970

Answer

You are getting confuse with the time zone. Try the following:

long strt = System.currentTimeMillis();// 1462968291733
    Thread.sleep(5000);
    long end = System.currentTimeMillis();// 1462968296733

    long diff = end - strt;


    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(diff);
    TimeZone cutsomTimeZone = TimeZone.getTimeZone("IST");

     DateFormat formatter = new SimpleDateFormat
                ("EEE MMM dd HH:mm:ss zzz yyyy");
    formatter.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
    System.out.println(formatter.format(calendar.getTime()));//

    formatter.setTimeZone(cutsomTimeZone);
    System.out.println(formatter.format(calendar.getTime()));

First, as the javadoc says, System.currentMillis() return the number of milliseconds since 1 January 1970 in UTC which is obviously different from IST.

Second, the Date object return by calendar.getTime() does not bear a timezone. The output you get with System.out.println(calendar.getTime()) use the default TimeZone of your system which seems to be IST.

Third, please don't use the Date api, it is really bad. When possible, prefer the java.time one.