Search code examples
grailsgroovyjodatimegsp

How to override Joda-Time GSP tag output


I am using the Joda-Time plug-in for Grails, and so far it has been a huge help. A massive improvement over the Java Date/Callendar method. Anyway, I am rendering Period data using the GSP tags as follows:

<joda:formatPeriod value="${ shift?.totalTime }" fields="hours,minutes" />

The tag renders the HTML as, 11 hours and 32 minutes. That's great but I need to override the text and change it to 11hrs. 32min..

Does anyone have experience doing this? I haven't found any examples as I've Googled the interwebs. I think this would help many others, as well.

BTW: I am really grateful to the Joda-Time creators. It's one of the most useful libraries/plugins I've found.


Solution

  • If you aren't concerned about localized text and will only have hours and minutes, then a simple solution would be to write your own little tag to do the formatting. Something like:

    def formatPeriod = { attrs ->
        def periodFormatter = new PeriodFormatterBuilder().appendHours().appendSuffix("hrs.").appendSeparator(" ").appendMinutes().appendSuffix("min.").toFormatter()
    
        out << periodFormatter.print(attrs.value)
    }
    

    Here's sample output from a groovy shell:

    groovy:000> period = new Period().withHours(11).withMinutes(32)
    ===> PT11H32M
    groovy:000> formatter = PeriodFormat.wordBased()
    ===> org.joda.time.format.PeriodFormatter@6d2ddeee
    groovy:000> formatter.print(period)
    ===> 11 hours and 32 minutes
    groovy:000> periodFormatter = new PeriodFormatterBuilder().appendHours().appendSuffix("hrs.").appendSeparator(" ").appendMinutes().appendSuffix("min.").toFormatter()
    ===> org.joda.time.format.PeriodFormatter@56048075
    groovy:000> periodFormatter.print(period)
    ===> 11hrs. 32min.