1

I want to calc the time differnce from when the user pressed start and stop. This is what I got so far:

Done in not worker thread:

runTime = System.currentTimeMillis();

Done on main thread:

DateFormat formatter = new SimpleDateFormat("hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis() - runTime);
timeTextView.setText("Time: " + formatter.format(calendar.getTime()));

The result is always "01:00:00.000". How come I get a 1hour added to the time? And ofc I press the start and stop button faster then one hour.

Jedi Schmedi
  • 746
  • 10
  • 36

3 Answers3

0

A simple way of solving (working around ?) this issue:

long startTime = System.currentTimeMillis();

//* do something

long endTime = System.currentTimeMillis();

long elapsedTimeInMilliSecs=(endTime - startTime);

Calendar ...

I use something like this and it works fine.

IanB
  • 3,489
  • 1
  • 20
  • 24
0

The result you have is the time since epoch in java, So if you try to print

timeTextView.setText("Time: " + calendar.getTime().toString());

You are more likely to have the result of Wed Dec 31 19:00:00 EST 1969 depends on which TimeZone you currently are. From your code above I got 07:00:00:000 because I am at EST TimeZone. You cant really do about it but it eliminate the hh so it will only show the minutes, seconds, and milliseconds.

Community
  • 1
  • 1
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
0

Try this if you just want your elapsed time in HH:MM:SS, this works even if you have more than 24 hours.

timeTextView.setText("Time: " + convertMillis(System.currentTimeMillis() - runTime));
...
public static String convertMillis(long milliseconds){  
    long time = milliseconds / 1000;  
    String seconds = Integer.toString((int)(time % 60));  
    String minutes = Integer.toString((int)((time % 3600) / 60));  
    String hours = Integer.toString((int)(time / 3600));  
    for (int i = 0; i < 2; i++) {  
        if (seconds.length() < 2) {  
            seconds = "0" + seconds;  
        }  
        if (minutes.length() < 2) {  
            minutes = "0" + minutes;  
        }  
        if (hours.length() < 2) {  
            hours = "0" + hours;  
         }  
    }  
    return(hours + ":" + minutes + ":" + seconds);  
}  
Guillaume Barré
  • 4,168
  • 2
  • 27
  • 50