Print duration in human readable EL format

First of all, I am new to java.time package.

I am writing a webapp that should work with certain times of the day and with multiple duration events.

So, I wrote my code using the LocalTime and Duration classes of the LocalTime package.

When I need to display their value in JSP, it is very simple for the LocalTime object (because .toString() returns a human readable scale), so I can just write ${startTime} and everything goes correctly (for example, it displays as 9:00 ). The same approach does not work for Duration, since its representation is something like PT20M (in this case, for 20 minutes).

Is there an elegant way to perform conversion to JSP directly using EL?

Yes, I know that I can convert an object to a string in my classes (before JSP), but I'm looking for a suggested approach (which I cannot find) ... another point is that I do not see the official method "convert () "(or any other) in the Duration object ... so I think I'm using the wrong object to display the length of time (to add or subtract LocalTime s).

Thanks.

+5
source share
1 answer

Unfortunately, there is no elegant built-in way to format Duration in Java 8. The best I have found is to use the bobince method described in this :

  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))); 

What prints:

1:20:00

The code should be customized if you need more time.

I'm not sure if you mean that you do not need the convert method, but Duration is good for adding / subtracting on LocalTime . The LocalTime.plus() and LocalTime.minus() methods take Duration as an argument.

+5
source

All Articles