register
other register

Tuesday, September 15, 2009

Calendar datepicker Plugin in Grails

Refer to Grails Calendar Plugin site for how to install and use the plugin.

<g:form>
<calendar:datePicker name="myDate" defaultValue="${new Date()}" dateFormat="%d/%m/%Y"/>
<g:actionSubmit name="myAction" value=Submit"/>

There will be some html and javascript code generated by the plugin when viewing page source. The code we care is:

...
<input type="text" id="myDate_value" name="myDate_value" readonly="true"/>
...

The submitted myDate will be in String format dd/mm/YYYY, and we will use myDate_value in our controller to retrieve value.

class MyController {
def myAction = {
if (params['myDate_value'] != null) {
def f = new SimpleDateFormat("dd/MM/yyyy")
def myDate = f.parse(params['myDate_value'])

// Testing
println myDate.class // it is java.util.Date
println myDate // Tue Sep 15 00:00:00 BST 2009

def test = Test.get(1)
println test.dateCreated.class //java.sql.Timestamp
println test.dateCreated // 2009-09-14 10:34:10.0

// Time comparison
println myDate > test.dateCreated // true
println myDate == test.dateCreated // false
println myDate < test.dateCreated // false
....
}
}
}

No comments: