Java pretty print for duration
Asked Answered
D

5

5

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

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

I need those strings in my web application to show how much it took to generate a file (in a pretty print way of course :) )

Thanks,

Dyne answered 27/8, 2010 at 21:23 Comment(0)
J
8

With JodaTime:

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

P.S. Also it's very easy to get the number of hours/seconds/minutes between 2 time points.

Jenjena answered 27/8, 2010 at 21:30 Comment(0)
O
3

Using JodaTime is the best overall approach, but here's one way to do it without using any domain-specific libraries, using the ChoiceFormat indirectly in the context of a 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();
}

Now you can have (as seen on 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

You can of course extend this to include days/months/years/etc.

Otic answered 28/8, 2010 at 4:33 Comment(0)
A
2

you can get the hours, minutes and seconds from java Calendar class and then concat them with what ever you like (hours , mins ...)

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);
...
Alaric answered 27/8, 2010 at 21:28 Comment(0)
S
1

This sounds very much like TimeAgo. You may be able to leverage the code in there to format durations like this.

Sheedy answered 27/8, 2010 at 21:27 Comment(0)
K
1

Try using SimpleDateFormat: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Kellie answered 27/8, 2010 at 21:39 Comment(1)
With the right TimeZone, it's feasible: stackoverflow.com/questions/2705674Dulse

© 2022 - 2024 — McMap. All rights reserved.