Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a Duration in human readable format by EL

Tags:

java

jsp

java-8

First of all I'm new to java.time package.

I'm writing a webapp that need to work with specific times of the day and with several durations of events.

So I wrote my code using LocalTime and Duration classes of java.time package.

When I need to render their value in JSP it is very simple for LocalTime object (because .toString() returns a human readable vale), so I can just write ${startTime} and everything goes in the right way (e.g. it is rendered as 9:00). The same approach doesn't work for Duration, because its representation is something like PT20M (in this case for 20 minutes).

Does it exist an elegant way to perform a human-readable conversion in JSP directly by EL?

Yes, I know I can convert the object in a string in my classes (before JSP), but I'm searching for the suggested approach (that I'm not able to find)... another point is that I not see an official "convert()" (or whatever else) method in Duration object... so I'm thinking I'm using the wrong object to map a duration of time (to add or subtract on LocalTimes).

Thank you.

like image 911
Pierpaolo Cira Avatar asked Jun 27 '15 17:06

Pierpaolo Cira


2 Answers

Unfortunately there exists no elegant builtin way to format a Duration in Java 8. The best i have found is to use the method bobince describes in this answer:

    Duration duration = Duration.ofHours(1).plusMinutes(20);
    long s = duration.getSeconds();
    System.out.println(String.format("%d:%02d:%02d", s/3600, (s%3600)/60, (s%60)));

Which prints:

1:20:00

The code will have to be tuned if you need longer durations.

I'm not sure what you mean that you are missing a convert method, but Duration is well suited for adding/subtracting on LocalTime. The methods LocalTime.plus() and LocalTime.minus() accepts Duration as argument.

like image 127
K Erlandsson Avatar answered Oct 27 '22 23:10

K Erlandsson


If you're interested in words, apache commons will do the trick:

 DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - start, true, false))
 2 days 1 hour 5 minutes 20 seconds

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DurationFormatUtils.html#formatDurationWords-long-boolean-boolean-

like image 4
Charlie Avatar answered Oct 28 '22 01:10

Charlie