2010-10-24 174 views
2

我有一個擁有人生日期的日期對象。我的代碼如下所示:試圖在groovy中計算年齡

def getAge(){ 
    //birthday, birthYear, birthMonth, birthDayOfMonth are class level properties 
    def c= new GregorianCalendar(birthYear, birthMonth-1, birthDayOfMonth) 
    birthday = c.time 
    //What do I do now? 
} 

我需要返回此人的年齡。我如何在Groovy中做到這一點?年齡只需要是一個整數。

回答

6

您可以只創建一個日曆當前日期和使用年計算的年齡:

def now = new GregorianCalendar() 
def fake = new GregorianCalendar(now.get(Calendar.YEAR), birthMonth-1, birthDayOfMonth) 
return now.get(Calendar.YEAR) - birthYear - (fake > now ? 1 : 0) 

假日期是用來理解,如果生日是在本年度已經過去了,如果不是,那麼你必須1。減去多年的區別..

3

我知道這是問題是舊的,但它激發了我創建這個功能,工作日期:

static Integer calculateAge(Date birthday, Date offset = new Date()) { 
    def birthdayThisYear = offset.clone().clearTime() 
    birthdayThisYear[MONTH]= birthday[MONTH] 
    birthdayThisYear[DATE] = birthday[DATE] 

    offset[Calendar.YEAR] - birthday[Calendar.YEAR] - (birthdayThisYear > offset ? 1 : 0) 
} 

你可以單獨用生日來計算今天的年齡,或者用第二個參數來計算年齡,即你想計算人的年齡的日期。使用的

+0

1;請注意,如果使用舊版本的groovy,則需要將'clearTime()'放在單獨的行上,因爲直到版本1.8左右纔會返回日期對象。 – 2013-11-25 21:12:47

0
Date.metaClass.calculateAge = { Date offset = new Date() -> 
     def birthdayThisYear = offset.clone().clearTime() 
     birthdayThisYear[Calendar.MONTH]= delegate[Calendar.MONTH] 
     birthdayThisYear[Calendar.DATE] = delegate[Calendar.DATE] 
     return offset[Calendar.YEAR] - delegate[Calendar.YEAR] - (birthdayThisYear > offset ? 1 : 0) 
    } 

例如:

def dateParser = new java.text.SimpleDateFormat("yyyy-MM-dd") 
dateParser.lenient = false 

dateParser.parse('1980-02-23').calculateAge()