4

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.

Scott
  • 16,711
  • 14
  • 75
  • 120
  • My plan right now is to just pass the .time portion of the date, but if Grails has some magic I don't know about and can't find, would rather use that. – Scott May 19 '11 at 15:55

3 Answers3

9

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.

Amit Jain
  • 1,372
  • 8
  • 16
4

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')
MKB
  • 7,587
  • 9
  • 45
  • 71
4

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

Community
  • 1
  • 1
Dónal
  • 185,044
  • 174
  • 569
  • 824
  • Do you have your `parse(String, String)` parameters backwards? [Groovy Date Specification](http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#parse%28java.lang.String,%20java.lang.String%29) – ubiquibacon Oct 15 '11 at 01:15
  • @typoknig you're right the params were in the wrong order - I've corrected the error – Dónal Nov 04 '11 at 17:01