Reputation: 17037
I have seen a few posts related to using the g:datePicker in Grails. Using this it looks like you can just pick the value off the params like so params.myDate.
However, when I try to do something like this in my view:
view:
<g:link controller="c" action="a" params="[fromDate:(new Date())]">
controller:
def dateval = params.fromDate as Date
The date is not parsing out correctly. Is there something else I should be doing in the view to make the date 'parsable' by the controller. I've looked around and haven't found this in any posts where datePicker is not used.
Upvotes: 4
Views: 10698
Reputation: 7619
Whatever is sent from view is a string so params.fromDate as Date
does not work.
In grails 2.x a date method is added to the params object to allow easy, null-safe parsing of dates, like
def dateval = params.date('fromDate', 'dd-MM-yyyy')
or you can pass a list of date formats as well, like
def dateval = params.date('fromDate', ['yyyy-MM-dd', 'yyyyMMdd', 'yyMMdd'])
or the format can be read from the messages.properties via key date.myDate.format
and use date method of params as
def dateval = params.date('fromDate')
Upvotes: 5
Reputation: 187499
When the parameters are sent to a controller they are sent as strings. The following won't work
def dateval = params.fromDate as Date
Because you haven't specified what date format to use to convert the string to a date. Replace the above with:
def dateval = Date.parse('yyyy/MM/dd', params.fromDate)
Obviously if your date is not sent in the format yyyy/MM/dd
you'll need to change the second parameter. Alternatively, you can make this conversion happen automatically by registering a custom date editor
Upvotes: 4
Reputation: 1382
I prefer to send time instead of dates from the client.
<g:link controller="c" action="a" params="[fromDate:(new Date().time)]">
And in action I use the constructor of Date that takes time.
def date = params.date
date = date instanceof Date ? date : new Date(date as Long)
I have created a method in DateUtil class to handle this. This works fine for me.
Upvotes: 9