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 (eg 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 LocalTime
s).
Thank you.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.