Thursday, July 31, 2008

Creating a new Grails tag to convert military time to standard time

I have a situation where I need to store time as military time (i.e. 0900 is 9:00 AM), but I want to display it as standard time. So, I created a new tag library in Grails to perform this for me. I then simply use the new tag in my gsp page, and all is well. Here's the code you would put in your taglib directory:

class MyTagLib {
def standardTime = {attrs, body ->
out << showStdTime(body())
}

def showStdTime(militaryTime) {
def hours
def minutes
def ampm = "AM"
if (militaryTime.trim().size() != 4) {
return militaryTime
}
try {
hours = new Integer(militaryTime[0..1])
minutes = militaryTime[2..3]

if (hours > 12) {
ampm = "PM"
hours -= 12
}

if (hours == 12) {
ampm = "PM"
}

if (hours == 0) {
hours = 12
}
} catch (Exception e) {
return "Format Exception: " + e.toString()
}

return hours + ":" + minutes + " " + ampm
}
}

And here's the tag as it looks in my gsp page (substitute the lt for <>. I couldn't get the formatting working right):

<g:standardtime>${myClass.closingTime}</g:standardTime>