Tuesday, September 04, 2007

Grails SQL date formating lib

Been working with Grails more and created a little tag lib I thought I would post up for others. The date that comes out of the domains is a rather ugly SQL date style so I create a tag lib with the following code:

 def formatSqlDate = { attrs -> 
def String startdatetime = "${attrs['targetDate']}"
def DateFormat odf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
def DateFormat df = new SimpleDateFormat( "MMM d, ''yy" );
out << df.format(odf.parse(startdatetime))
}
Then I can simple reference it with:

<g:formatsqldate targetdate="${domain.dateObject}">

A person can mode the date format string all they want and also could put in various cases or a flag to select a format style if they wished.

4 comments:

Sanj said...

nice one thanks was pretty useful for me!

Sanj said...

Seems sql.date inherits from util.date so wondering why theres a need to convert to string and reconvert, rather than format the sql date object directly....

fils said...

Sanj,
It does seem odd.. I did find one could do this. Say you have an sqlDate object, then:

long milliseconds = sqlDate.getTime() + (sqlDate.getNanos() /1000000)

def theDate = new Date(milliseconds)

or all on one line of course if you wish too . :)

Jerm said...

mind the targetDate vs targetdate

this caused me some head scratching