Christian Christian - 1 year ago 135
Android Question

How do I convert a jodatime Duration into a string formatted as hh:mm:ss?

I'm using the jodatime library. I want to display a count-down between now and an end time and display it to the user. I get the duration that I want to display via:

Interval time = new Interval(, end_time);
Duration duration = time.toDuration();

Now I want to convert the duration into a string formatted as
. What is the most straightforward way to do this?

Answer Source

Use the DurationUtils from apache.commons.lang:

import org.apache.commons.lang.time.DurationFormatUtils;

DurationFormatUtils.formatDuration(duration.getMillis(), "HH:mm:ss")

Or you use:

DateFormat df = new SimpleDateFormat("hh:mm:ss");
String formatted = df.format(new Date(duration.getMillis()));

Or another very short solution:

String formatted = String.format("%1$tI:%1$tM:%1$tS", duration.getMillis());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download