Groovy TimeDuration Argument Types

366 Views Asked by At

I'm quite new to groovy (and haven't any experience with Java) - but I'm running into a problem that doesn't make sense to me. My guess is that its my misunderstanding of how objects and classes work in these languages. My question is probably very basic - any help is greatly appreciated.

I'm trying to calculate the number of weeks between two dates. My code is this (it could be more succinct, but I've expanded it to make each step more clear):

import groovy.time.TimeCategory

start = new Date(year: 2014, month: Calendar.APRIL, date: 1, hours: 12, minutes: 12, seconds: 0)
finish = new Date(year: 2014, month: Calendar.MAY, date: 4, hours: 1, minutes: 12, seconds: 0)


use ( TimeCategory ) {
    diff = finish - start
    println getWeeks(diff)       
}

I get an error

groovy.lang.MissingMethodException: No signature of method: Script1.getWeeks() is applicable for argument types: (groovy.time.TimeDuration) values: [32 days, 13 hours]

However, if I change the print line to println diff.getClass().name

My results output is

groovy.time.TimeDuration

So my question is essentially: if the diff object is of the class groovy.time.TimeDuration and the getWeeks requires arguments of this class, why do I get an error?

1

There are 1 best solutions below

0
On BEST ANSWER

you should be using:

use ( TimeCategory ) {
    diff = finish - start
    println diff.weeks 
}

what you see in the groovy doc static Duration getWeeks(Integer self) is the how the groovy system calls the methods.

Almost all such static groovy methods have this form: static doSmth( self, otherArgs... ) and you have to call it as self.doSmth( otherArgs... )