Reputation: 3394
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.
Upvotes: 2
Views: 3433
Reputation: 353
Date.metaClass.calculateAge = { Date offset = new Date() ->
def birthdayThisYear = offset.clone().clearTime()
birthdayThisYear[Calendar.MONTH]= delegate[Calendar.MONTH]
birthdayThisYear[Calendar.DATE] = delegate[Calendar.DATE]
return offset[Calendar.YEAR] - delegate[Calendar.YEAR] - (birthdayThisYear > offset ? 1 : 0)
}
example of use:
def dateParser = new java.text.SimpleDateFormat("yyyy-MM-dd")
dateParser.lenient = false
dateParser.parse('1980-02-23').calculateAge()
Upvotes: 0
Reputation: 3124
I know this is question is old, but it inspired me to create this function, working on dates:
static Integer calculateAge(Date birthday, Date offset = new Date()) {
def birthdayThisYear = offset.clone().clearTime()
birthdayThisYear[MONTH]= birthday[MONTH]
birthdayThisYear[DATE] = birthday[DATE]
offset[Calendar.YEAR] - birthday[Calendar.YEAR] - (birthdayThisYear > offset ? 1 : 0)
}
You can either call it with the birthday alone to calculate the age today, or with a second argument, being the date where you want to calculate the persons age.
Upvotes: 4
Reputation: 133609
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..
Upvotes: 6