oshai
oshai

Reputation: 15365

How to display time amount to user?

I want to convert time amount from milli-sec to a human readable string.

For example:

3,600,000 should be displayed as 1:00:00 (1 hour).

Is there an existing library or class in Java that can do that?

Upvotes: 1

Views: 202

Answers (1)

bilash.saha
bilash.saha

Reputation: 7316

Since 1.5 there is the java.util.concurrent.TimeUnit class, use it like this:

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

For Versions below 1.5 You have to use

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

Upvotes: 3

Related Questions