Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate age in Groovy from today

Tags:

groovy

Trying to figure out how old someone is based on their bday. The following code gives us the number of days

def now = new Date()
def dob = new Date('08/21/1982')

println now - dob

We could divide by 365 but that isn't entirely accurate. There has to be an easy way to do this but I just can't seem to find it. Any ideas?

like image 428
Dan Vega Avatar asked Nov 24 '25 15:11

Dan Vega


1 Answers

Or using Java 8 and Groovy 2.3 RC (if you want to be on the bleeding edge) ;-)

import java.time.*

LocalDate today    = LocalDate.now()
LocalDate birthday = LocalDate.of( 1982, Month.AUGUST, 8 )

Period period = Period.between( birthday, today )

println """$period.years years, 
          |$period.months months, 
          |$period.days days""".stripMargin()
like image 74
tim_yates Avatar answered Nov 27 '25 23:11

tim_yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!