0

I am working on Controller Test in Grails 2.2.3 and I have a Date field in a Domain. However when you are testing Controller you suppose to put everything into params and apparently params must have everything in Strings.

How do I put Date into params?

Example of params:

    params["issueNumber"] = 1
    params["dateOfIssue"] = "2014-05-16 09:17:38 EDT"
    params["placements"] = [location:"Sample location", page:1, column:1, row:1]
    params["newsPaper"] = [name:"Sample Ad Name"]

For "placements" & "newsPaper" - they are param representation of other domains. Above example fails on controller.save() and doesn't output much of useful information.

Thank you.

MeIr
  • 7,236
  • 6
  • 47
  • 80

3 Answers3

1

It depends on the way params is bound to a command object or domain class, if it is bound at all. Considering a domain class is directly bound in the controller action which has a field named dateOfIssue, below is the default date format that has to be used

yyyy-MM-dd HH:mm:ss.S

Now this can also be customized globally if you are using Grails 2.3.* by providing config settings for date formats by adding grails.databinding.dateFormats as:

grails.databinding.dateFormats = [
    'MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', "yyyy-MM-dd'T'hh:mm:ss'Z'"
]

Refer date formats for data binding docs for details.

For Grails 2.2.3, refer this question in order to bind a custom date format. Hope that helps.

Also, keeping aside the whole data binding stuff, if that is not being used at all, then obviously whichever format is standardized for your app below transformation can be used to get a date from String:

Date.parse("yyyy-MM-dd HH:mm:ss Z", "2014-05-16 09:17:38 EDT")
Community
  • 1
  • 1
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
0

I discovered another way to pass date via params that might not be as pretty as dmahapatro provided but it doesn't require any modifications. Example:

    params["dateOfIssue"] = "Fri May 16 00:00:00 EDT 2014"
    params["dateOfIssue_year"] = "2014"
    params["dateOfIssue_month"] = "5"
    params["dateOfIssue_day"] = "16"

Original field name is "dateOfIssue".

Community
  • 1
  • 1
MeIr
  • 7,236
  • 6
  • 47
  • 80
0

You can create a StringToDateValueConverter to accomplish this.

See this (it is also locale aware)

Community
  • 1
  • 1
mpccolorado
  • 817
  • 8
  • 16