Java pretty prints for duration

Is there a Java class or some sample code that can convert java Date or Timestamp into something like:

"3 hours"
" 20 seconds"
 "25 minutes"

I need these lines in my web application to show how much it takes to generate the file (in pretty printed form, of course :))

Thank,

+5
source share
5 answers

With JodaTime :

PeriodFormat.getDefault( ).print( Hours.THREE );
PeriodFormat.getDefault( ).print( Seconds.seconds( 25 ) );
PeriodFormat.getDefault( ).print( Minutes.minutes( 20 ) );

PS It is also very easy to get the number of hours / seconds / minutes between 2 time points.

+8
source

JodaTime - , - , ChoiceFormat MessageFormat:

static String choiceFor(int index, String noun) {
    return "{index,choice,0#|1#1 noun |1<{index,number,integer} nouns }"
        .replace("index", String.valueOf(index))
        .replace("noun", noun);
}
static String prettyPrint(int h, int m, int s) {
    String fmt = 
        choiceFor(0, "hour") +
        choiceFor(1, "minute") +
        choiceFor(2, "second");
    return java.text.MessageFormat.format(fmt, h, m, s).trim();
}

( ideone.com):

    System.out.println(prettyPrint(1,2,3));
    // 1 hour 2 minutes 3 seconds

    System.out.println(prettyPrint(0,0,7));
    // 7 seconds

    System.out.println(prettyPrint(1,0,1));
    // 1 hour 1 second

    System.out.println(prettyPrint(0,2,0));
    // 2 minutes

, , , // ..

+3

, java Calendar, , (, ...)

Calendar c = Calendar.getInstance();
c.setTimeinMillis(<the time in milli second format (a long number)>);

int hours = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MIN);
...
+2

TimeAgo. , , .

+1

All Articles