Leigh8347
Leigh8347

Reputation: 91

android - time difference

I have looked at the other Q&A regarding this subject but didn't find anything that helped.

My app records race results and saves to file.

On 1st click it writes the current time, and when a runner is finished, it records the current time again.

How can I calculate both times to get race time?

Here is how I get the current time:

public class Stopwatch extends Activity {
// GUI controls
Button startRun;
Button checkIn;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setRequestedOrientation(
        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.stopwatch); 

        final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");


         startRun = (Button) findViewById(R.id.start);
        startRun.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/timer.txt"));
            out.write("Race start time" + "," + dateFormat.format(new Date()));
            out.write("\r\n");
            out.close();
        } catch (Exception e) {
        }

        startRun.setEnabled(false);

    }
    });

        checkIn = (Button) findViewById(R.id.counter);
        checkIn.setOnClickListener(new OnClickListener() {

            private int entryCounter = 1;

        public void onClick(View v) {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/timer.txt", true));
            out.write(entryCounter +  "," + dateFormat.format(new Date()) + "," ***time difference here***);
            entryCounter++;
            out.write("\r\n");
            out.close();
        } catch (Exception e) {
        }

    }
    });



    }

}

i am looking for a format like this

0,01/10/2011 09:02:00
1,01/10/2011 09:18:42,00:16:42
2,01/10/2011 09:18:42,00:16:42
3,01/10/2011 09:20:07,00:18:07

Upvotes: 2

Views: 865

Answers (2)

Franziskus Karsunke
Franziskus Karsunke

Reputation: 5208

You should use the method currentTimeMillis()

long millisecondssince1970 = System.currentTimeMillis();

after that you can get the new time and calculate the difference

long newTime = System.currentTimeMillis();
long raceTimeinMilliseconds = newTime - millisecondssince1970;

In addition to this you can use the getTime() method of Date objects to do this. This method returns a millisecond value as well.

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 691765

long start = System.currentTimeMillis();
// ... the race 
long end = System.currentTimeMillis();
long raceDurationInMillis = end - start;

You may be more precise and use System.nanoTime, but I doubt it will make a significant difference.

Upvotes: 1

Related Questions