-1

我写了一段代码,可以生成更接近现实生活的年龄。我假设我们每年都会在遇到生日的那一天和一个月的时候增加我们的年龄,所以从技术上讲,有些年份更长,有些年份更短,但对我们这些人来说并不重要。这是我想出的解决方案,我基本上想在这里分享我的解决方案,如果有人有更好的方法分享,我也很感激。

def today= new GregorianCalendar()
def dob= new GregorianCalendar()
dob.set(Calendar.ERA, GregorianCalendar.AD )
dob.set(Calendar.YEAR, 1983 )
dob.set(Calendar.MONTH, Calendar.MAY )
dob.set(Calendar.DATE, 23)


userMonth=dob.get(Calendar.MONTH)
userDay=dob.get(Calendar.DATE)
todayMonth=today.get(Calendar.MONTH)
todayDay=today.get(Calendar.DATE)

if(todayMonth < userMonth && todayDay < userDay){
    println today.get(Calendar.YEAR)-dob.get(Calendar.YEAR)-1
}else{
    println today.get(Calendar.YEAR)-dob.get(Calendar.YEAR)
}
4

1 回答 1

0

这是一个开放式问题,因此您可能需要考虑将其转变为不那么主观的问题。

话虽如此,我的看法是使用joda-time,在这种情况下,您可以执行以下操作:

import org.joda.time.DateTime
import org.joda.time.Years

def yob = new DateTime(1983, 12, 10, 0, 0).toDateMidnight()
def now = DateTime.now().toDateMidnight()

def years = Years.yearsBetween(yob, now).getYears()

println "Years: $years"

如果你只是想分享你的代码供其他人使用(顺便说一句,这很棒),也许你想创建一个 gist

[编辑] 我刚刚创建了一个,在这里

祝你好运!

于 2013-12-10T20:55:11.537 回答