-1

I have tried the following code and still get the same results:

Code1

    long start=System.currentTimeMillis();

    try {
        Thread.sleep(3000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    long finish=System.currentTimeMillis();

    Date date1 = new Date(finish- start);
    DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
    String dateFormatted = formatter.format(date1);
    System.out.println(dateFormatted);

Code2

 Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(appTerminateTime - appStartTime);
    return "session lasted for " + calendar.get(Calendar.HOUR) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND);
apicellaj
  • 233
  • 1
  • 3
  • 16
skystar7
  • 4,419
  • 11
  • 38
  • 41

1 Answers1

1

The reason for the extra hours is because of the difference between your time zone and the default GMT of the JVM when creating the Date.

It's not clear what session length you're trying to measure, but you might consider System.nanoTime() for a more precise length of measurement since using System.currentTimeMillis() may introduce errors as it has corrections for wall-clock time as seen in this answer.

Community
  • 1
  • 1
apicellaj
  • 233
  • 1
  • 3
  • 16