Grails has 3 clean formatting tag libraries:
Wonder if there is one to format seconds into HH:MM:SS? or if there is another elegant way to format seconds in the rendered view.
Note:
formatDate
does not work since there might be more seconds than 86400
.
So for a duration of 86461
formatDate
will return a 00:01:01
where in fact it should be 24:01:01
.
You could create a tag lib: Put SecondsTagLib.groovy
into grails-app/taglib/
(both the location, and the suffix TagLib
in the class name do matter).
class SecondsTagLib {
def formatSeconds = {
attrs, body ->
final int hours = attrs.seconds / (60 * 60)
final int remainder = attrs.seconds % (60 * 60)
final int minutes = remainder / 60
final int seconds = remainder % 60
out << hours.toString().padLeft(2, "0") + ":" + minutes.toString().padLeft(2, "0") + ":" + seconds.toString().padLeft(2, "0")
}
}
and use that taglib in your view:
<html>
<body>
Seconds: ${seconds} = <g:formatSeconds seconds="${seconds}"/>
</body>
</html>
the controller's method could look like this:
class TagLibController {
def seconds() {
// 10:11:01
def seconds = (10 * 60 * 60) + (11 * 60) + 1
def model = ["seconds": seconds]
render(view: "seconds", model: model)
}
}