试图弄清楚某人有多大年纪。以下代码为我们提供了天数
def now = new Date()
def dob = new Date('08/21/1982')
println now - dob
我们可以除以365,但这并不完全准确。必须有一个简单的方法来做到这一点,但我似乎无法找到它。有任何想法吗?
答案 0 :(得分:6)
或者使用Java 8和Groovy 2.3 RC(如果你想处于最前沿); - )
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()
答案 1 :(得分:4)
这是一个使用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()
答案 2 :(得分:1)
对我来说,joda不可用,所以我搜索了另一个更加常规的解决方案并找到了:
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;
答案 3 :(得分:-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
}
}