Reputation: 1107
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?
Upvotes: 3
Views: 5516
Reputation: 1
def current = new Date()
println current
def dob = new Date ('06/27/2000')
println dob
def res = current - dob
def age = res/365
println age
Upvotes: 0
Reputation: 1
import com.sap.it.api.mapping.*;
import java.util.HashMap;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;
import groovy.time.TimeCategory;
import groovy.time.TimeDuration;
def String customFunc(String DOB){
if(DOB == '')
{
DOB = '';
return DOB;
}
else
{
Date birth_yr=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(DOB);
Date date = new Date();
def duration = groovy.time.TimeCategory.minus(date,birth_yr);
def age = (duration.days).intdiv(365)
return age
}
}
Upvotes: -1
Reputation: 720
For me joda was not available so I searched another, more groovy solution and found:
def duration = groovy.time.TimeCategory.minus(
new Date(),//date1
new Date(session.creationTime)//date2
);
println "seconds: " + dur2.seconds;
println "min: " + dur2.minutes;
println "hours: " + dur2.hours;
Upvotes: 1
Reputation: 171154
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()
Upvotes: 6
Reputation: 50265
Here is a sleek alternative using joda time :)
@Grab('joda-time:joda-time:2.3')
import org.joda.time.Period
import org.joda.time.DateTime
def now = new DateTime()
def dob = new DateTime(1982, 8, 21, 0, 0)
def period = new Period(dob, now)
println """$period.years years,
|$period.months months,
|$period.days days,
|$period.hours hours,
|$period.minutes minutes
""".stripMargin()
Upvotes: 4