views:

32

answers:

1

I have a date object that holds a persons birthday. My code looks like:

def getAge(){
    //birthday, birthYear, birthMonth, birthDayOfMonth are class level properties
    def c= new GregorianCalendar(birthYear, birthMonth-1, birthDayOfMonth)
    birthday = c.time
    //What do I do now?
}

I need to return the age of the person. How do I do that in Groovy? The age only needs to be a integer.

+1  A: 

You can just create one calendar with the current date and use the year to compute age:

def now = new GregorianCalendar()
def fake = new GregorianCalendar(now.get(Calendar.YEAR), birthMonth-1, birthDayOfMonth)
return now.get(Calendar.YEAR) - birthYear - (fake > now ? 1 : 0)

the fake date is used to understand if birthday is already passed in current year, if it's not then you must substract 1 to the difference between years..

Jack