How to pass date values ​​as parameters in Grails

I saw several posts related to using g: datePicker in Grails. Using this, it looks like you can simply select a value from parameters, for example params.myDate.

However, when I try to do something like this in my opinion:

View:

<g:link controller="c" action="a" params="[fromDate:(new Date())]"> 

controller:

 def dateval = params.fromDate as Date 

Date is not processed correctly. Is there anything else that I have to do in the view to make the date “parsed” by the controller. I looked around and did not find this in any posts where datePicker is not used.

+4
source share
3 answers

I prefer to send time rather than dates from the client.

 <g:link controller="c" action="a" params="[fromDate:(new Date().time)]"> 

And in action, I use the Date constructor, which takes time.

 def date = params.date date = date instanceof Date ? date : new Date(date as Long) 

I created a method in the DateUtil class to handle this. This works great for me.

+8
source

When parameters are sent to the controller, they are sent as strings. The following actions will not be performed.

 def dateval = params.fromDate as Date 

Because you did not specify which date format to use to convert the string to date. Replace above:

 def dateval = Date.parse('yyyy/MM/dd', params.fromDate) 

Obviously, if your date is not sent in yyyy/MM/dd format, you will need to change the second parameter. Alternatively, you can do this conversion automatically by registering your own date editor.

+4
source

Everything sent from the view is a string, so params.fromDate as Date does not work.

In grails 2.x, the date method is added to the params object, which allows easy, null-safe parsing of dates, for example

 def dateval = params.date('fromDate', 'dd-MM-yyyy') 

or you can also pass a list of date formats, for example

 def dateval = params.date('fromDate', ['yyyy-MM-dd', 'yyyyMMdd', 'yyMMdd']) 

or the format can be read from messages.properties using the date.myDate.format key and use the parameter date method as

 def dateval = params.date('fromDate') 
+2
source

All Articles