2

Here is some sample code from iOS:

NSDate *startDateX = [NSDate date];

// Do a bunch of stuff

NSLog(@"Time difference: %f", -[startDateX timeIntervalSinceNow]);

The output looks like this:

Time difference: 15.009682

What is the equivalent way to do this in Android/Java?

Ethan Allen
  • 13,766
  • 23
  • 96
  • 185

1 Answers1

7

You can use System.currentTimeMillis() to calculate milliseconds:

long start = System.currentTimeMillis();
// Do stuff
long difference = System.currentTimeMillis() - start;
Log.v("Time difference:", String.valueOf(difference));

If you want something more precise use System.nanoTime(). If you want seconds simply divide System.currentTimeMillis() by 1000.

There is the DateUtils class (android.text.format.DateUtils) that can calculate relative time differences like "5 mins ago". Also Joda Time is a great 3rd party library if you plan to do a lot of work with time.

Sam
  • 85,827
  • 19
  • 179
  • 175