Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)
I want to record the time using System.currentTimeMillis()when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.

What's the best way to do this?

1 Answer

0 votes
by (46k points)

To convert milliseconds to mins and seconds in Java use java.util.concurrent.TimeUnit class:

String.format("%d min, %d sec",  TimeUnit.MILLISECONDS.toMinutes(millis),  TimeUnit.MILLISECONDS.toSeconds(millis) - 

TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))

);

Note: TimeUnit is a component of the Java 1.5 spec, but toMinutes was annexed as of Java 1.6.

If you want to add a zero for values before your single digits like 0-9, just do:

String.format("%02d min, %02d sec", TimeUnit.MILLISECONDS.toMinutes(millis),

TimeUnit.MILLISECONDS.toSeconds(millis) - 

TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))

);

If TimeUnit or toMinutes aren't supported (like on Android's previous API version 9), you can use the equations given below:

int seconds = (int) (milliseconds / 1000) % 60 ;

int minutes = (int) ((milliseconds / (1000*60)) % 60);

int hours   = (int) ((milliseconds / (1000*60*60)) % 24);

//etc...

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 24, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...