Question

Found that code on this site and this code works for my case but is there a way that I can get the elapsed time "duration" directly and format it with SimpleDateFormat("HH:mm:ss")? To be more specific.. I want something like this without getting the HH:mm:ss from year 1970 :) , for example: "00:00:10"

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); duration = endTime-startTime; durationStr=sdf.format(duration);

      public long startTime;
      public long endTime;
      String durationStr;
      public long durationSec;
      public long minutes,seconds,hours;

        @Override
            public void onCreate(){
            super.onCreate();
            //service started
            startTime = System.currentTimeMillis();
        }

                public getLastLocation(){
            //this is where the service ends
                endTime=System.currentTimeMillis();
                Date d = new Date(endTime);
                Date d1 = new Date(startTime);
                duration = d.getTime() - d1.getTime();
                durationSec = TimeUnit.MILLISECONDS.toSeconds(duration);
                seconds = durationSec % 60;
                durationSec/= 60;
                minutes = durationSec % 60;
                durationSec /= 60;
                hours = durationSec % 24;
                durationStr=String.valueOf(hours)+" "+String.valueOf(minutes)+" "+String.valueOf(seconds);
Was it helpful?

Solution

You can try this:

Note: I'm not using any service in this example, so I've used a postDelayed which executes the code after 5 seconds. Based on that, I'm calculating the duration from the start of the activity to the end of the postDelayed

long delayedTime, currTime;
TextView text;
currTime = System.currentTimeMillis();
            new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        delayedTime = System.currentTimeMillis();
                        text.setText("" + getDurationString((int)((delayedTime - currTime) * 0.001)));
                    }
                }, 5000);

--

public String getDurationString(int seconds) {
    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    seconds = seconds % 60;
    return twoDigitString(hours) + " : " + twoDigitString(minutes) + " : " + twoDigitString(seconds);
                }

private String twoDigitString(int number) {
  if (number == 0) {
     return "00";
  }
  if (number / 10 == 0) {
     return "0" + number;
  }
  return String.valueOf(number);
}

[conversion]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top