Rammohan
Rammohan

Reputation: 619

Grails Date is being accepted as String

In my grails domain I am having a field Date i.e. java.util.Date.

In my controller I am loading this date from params using SimpleDateFormate.

To be precise assume that params.date is something like '20/02/2013 02:30 am'. In the controller I load this as follows:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm a"); domainInstance.date = simpleDateFormat.parse(params.date)

While this statement executes no error is detected. However when the domain Instance is being saved error is generated that

[typeMismatch.Domain.date,typeMismatch.date,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes

[Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date'; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "20/02/2013 02:30 am"]

Can you anyone tell me where things are going wrong. I am pretty sure that SimpleDateFormat parses String to Date. Why is it accepting as String.

Upvotes: 1

Views: 2877

Answers (3)

Zhuravskiy Vitaliy
Zhuravskiy Vitaliy

Reputation: 89

Grails 2.3.1 is actual problem

def domain = new FooBar(params)
domain.clearErrors()
domain.save(flush:true) // <--- validation will be there
if (doamin.hasErrors()) {
 ... do something
}

Upvotes: 1

Rammohan
Rammohan

Reputation: 619

Thanks for the response, but I have found the solution to the problem. The problem was something like this.

I was instantiating my domainInstance as domainInstance = new Domain(params) This was the first statement in the controller action.

When this statement is executed params holds the date in the format "dd/MM/yyyy HH:mm a". Hence this statement adds an error in the domainInstance object.

Later after using SimpleDateFormat the variable is updated but the error still remains in the object because of which the error crops up.

The solution to this error is immediately after the statement 'domainInstance = new Domain(params)' call the statement domainInstance.clearErrors().

This clears up all the errors in the object. Later when the domainInstance is being saved validate is called. In case validate fails due to some other error then the respective error is added at that time.

Rammohan

Upvotes: 5

uchamp
uchamp

Reputation: 2512

You can try:

domainInstance.date = new Date().parse("dd/MM/yyyy HH:mm a", params.date)

Upvotes: 0

Related Questions