Devin Rhode
Devin Rhode

Reputation: 25377

Grails basics:dates, strings, and object properties

I'm just starting out with Grails, transitioning from Javascript

In a controller, I'm trying to do this below, but I get an error

def list = {
  def projects = Project.list()

  projects.each {
    it.dateCreated = it.dateCreated.format('mm/dd')
    println it.dateCreated
  }
  return [projectInstanceList: projects, 
          projectInstanceTotal: projects.size()]
}

In my view I then display the dateCreated for a project, I just want to format the date so it's cleaner/more concise.

This is my error:

'java.lang.String' to class 'java.util.Date'

I also tried assigning this to it.dateCreated

new Date(2011, 09, 31, 10, 57, 00) 

But that gave a similar error also.

Upvotes: 0

Views: 236

Answers (3)

Colin Harrington
Colin Harrington

Reputation: 4459

Date.format(...) returns a String (see the documentation). You can't assign a java.lang.String to java.util.Date

Either println it.dateCreated.format('mm/dd') or use Grails' formatDate tag to render this in your view.

Upvotes: 1

Joshua Moore
Joshua Moore

Reputation: 24776

First, you should never change a domain instance property like that just for "display" purposes. The reason for that is the domain instance is actually going to be persisted with your changes when the hibernate session flushes.

Second, let the view display the property in the correct format. That's the responsibility of the view, not the domain instance, or the controller.

Upvotes: 2

skaz
skaz

Reputation: 22640

it.dateCreated is a java.util.Date. When you do: it.dateCreated.format('mm/dd') you are formatting the date but returning a java.lang.String. Then you try to assign that String to your it.dateCreated, but it can't take it, because it is a date.

Try just: println it.dateCreated.format('mm/dd')

Upvotes: 0

Related Questions