whitenexx
whitenexx

Reputation: 1360

How to sort Domain-Objects with attribute with type JodaTime / DateTime in grails 1.3.7?

I'm working on a small event calendar and i want to sort the events by start time!

I'm using JodaTime Plugin in grails for the startTime attribute. ( http://www.grails.org/JodaTime+Plugin )

So, how can i sort with this datatype? This does not work:

def sortedEvents = events.asList().sort({ a, b -> a.startTime <=> b.startTime } as Comparator)

I hope you can help me!

Thanks, whitenexx

/EDIT/ This is the code where i'm getting the events:

    def getEventsNext(Location location) {
        def events = location.events.findAll { it.endTime >= new DateTime() }
    def sortedEvents = events.sort{it.startTime}
    System.out.println(sortedEvents); //test
    return sortedEvents
}

In /event/list action everything works fine with g:sortableColumn (sorting by startTime): /event/list

Upvotes: 0

Views: 5971

Answers (3)

gotomanners
gotomanners

Reputation: 7926

Try overriding the compareTo method in your domain classes.

For example,

int compareTo(obj) {
    startTime.compareTo(obj.startTime)
} 

Edit

Sort your events like so:

def sortedEvents = events.sort{e1,e2-> e1.startTime.compareTo(2.startTime)}

Or as suggested by @Don, the groovier equivalent

def sortedEvents = events.sort{e1,e2-> e1.startTime <=> e2.startTime}

Upvotes: 1

user569825
user569825

Reputation: 2459

Try

def events = location.events.findAll { it.endTime.isAfterNow() }
def sortedEvents = events.sort{it.startTime.toDate()}

JavaDoc for isAfterNow()

Upvotes: 0

D&#243;nal
D&#243;nal

Reputation: 187539

Try this:

def sortedEvents = events.asList().sort{it.startTime}

To reverse the sorting order, use:

def sortedEvents = events.asList().sort{-it.startTime}

FYI, Groovy adds this sort() method to Collection so you can remove asList() from the code above if events is already a Collection.

Upvotes: 2

Related Questions