Computing the age in groovy - more realistic way

691 views Asked by At

I wrote a piece of code that generates the age more realistic to real life. I assume that we increment our age every year right when we meet the day and month of our birthday, so technically some years are longer and some are shorter, but to us people it doesn't matter. Here is the solution I came up with, I basically wanted to share my solution here, and I also appreciate if someone has a better approach to share.

def today= new GregorianCalendar()
def dob= new GregorianCalendar()
dob.set(Calendar.ERA, GregorianCalendar.AD )
dob.set(Calendar.YEAR, 1983 )
dob.set(Calendar.MONTH, Calendar.MAY )
dob.set(Calendar.DATE, 23)


userMonth=dob.get(Calendar.MONTH)
userDay=dob.get(Calendar.DATE)
todayMonth=today.get(Calendar.MONTH)
todayDay=today.get(Calendar.DATE)

if(todayMonth < userMonth && todayDay < userDay){
    println today.get(Calendar.YEAR)-dob.get(Calendar.YEAR)-1
}else{
    println today.get(Calendar.YEAR)-dob.get(Calendar.YEAR)
}
1

There are 1 answers

0
silverbeak On BEST ANSWER

This is an open-ended question, so you might want to consider turning it into something less subjective.

That being said, my take would be to use joda-time, in which case you could do something like this:

import org.joda.time.DateTime
import org.joda.time.Years

def yob = new DateTime(1983, 12, 10, 0, 0).toDateMidnight()
def now = DateTime.now().toDateMidnight()

def years = Years.yearsBetween(yob, now).getYears()

println "Years: $years"

If you just want to share your code for someone else to use (which, by the way, is awesome), perhaps you want to create a gist.

[EDIT] I just created one, here

Good luck!