Reputation: 14835
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?
Upvotes: 2
Views: 1934
Reputation: 403
Java
void test() {
Date startDateX = new Date(); // represents down to milliseconds
// Do a bunch of stuff
// ...
System.out.printf("%.3f", timeIntervalSinceNow(startDateX));
}
private Double timeIntervalSinceNow(Date date) { return 0.001 * (date.getTime() - System.currentTimeMillis()); } // The time interval between the date and the current date and time. If the date parameter is earlier than the current date and time, this property's value is negative.
Is equivalent to...
Objective-C
- (void) test {
NSDate *startDateX = [NSDate date];
// Do a bunch of stuff
// ...
NSLog(@"Time difference: %f", -[startDateX timeIntervalSinceNow]);
}
Or... Swift 5
func test() {
let startDateX = Date()
// Do a bunch of stuff
// ...
print(String(format: "Time difference: %f", -startDateX.timeIntervalSinceNow))
}
Upvotes: 0
Reputation: 86948
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.
Upvotes: 7