views:

90

answers:

3

In Java I have a long integer representing a period of time in milliseconds. The time period could be anything from a couple of seconds to a number of weeks. I would like to output this time period as a String with the appropriate unit.

For example 3,000 should be output as "3 seconds", 61,200,000 should be output as "17 hours" and 1,814,400,000 should be output as "3 weeks".

Ideally I would also be able to fine-tune the formatting of sub-units, e.g. 62,580,000 might be output as "17 hours, 23 minutes".

Are there any existing Java classes that handle this?

+5  A: 

The Joda library can do that for you:

PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
 .printZeroAlways()
 .appendYears()
 .appendSuffix(" year", " years")
 .appendSeparator(" and ")
 .printZeroRarely()
 .appendMonths()
 .appendSuffix(" month", " months")
 .toFormatter();
mhaller
A: 

Check out joda-time's format package

BranTheMan
+4  A: 

See also DurationFormatUtils in the Apache commons.

trashgod