从今天开始计算Groovy中的年龄

oxf4rvwz  于 2023-06-28  发布在  其他
关注(0)|答案(5)|浏览(150)

想根据一个人的生日来判断他的年龄。下面的代码给我们的天数

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

println now - dob

我们可以除以365,但这并不完全准确。必须有一个简单的方法来做到这一点,但我似乎找不到它。有什么想法吗

fxnxkyjh

fxnxkyjh1#

或者使用Java8和Groovy2.3RC(如果你想站在最前沿);- )

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()
mkshixfv

mkshixfv2#

下面是一个使用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()
s71maibg

s71maibg3#

对我来说,joda不可用,所以我搜索了另一个更groovy的解决方案,发现:

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;
vc9ivgsu

vc9ivgsu4#

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

xmakbtuz

xmakbtuz5#

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
} 
}

相关问题