您的位置:首页 > 其它

年龄Age的计算(可以精确到1岁3个月10天)

2011-06-28 21:45 302 查看
import java.text.SimpleDateFormat

/**
* 年龄对象(3岁、3个月、30天)
*/
class Age {
Integer age
AgeUnit unit

Integer year
Integer month
Integer day

Age() {

}

Age(int age) {
this.age = age
unit = AgeUnit.YearOfAge
}

Age(String str) {
def regular = /^(\d+)(\S+)?/
if (!(str ==~ regular)) {
throw new IllegalArgumentException("不是年龄格式")
}
def result = (str =~ regular)           //拆分
age = Integer.parseInt(result[0][1])
unit = result[0][2] ? AgeUnit.getUnitBySymbol(result[0][2]) : AgeUnit.YearOfAge
}

Age(int age, AgeUnit unit) {
this.age = age
this.unit = unit
}

Age(Date birthday) {
this(birthday, new Date())
}

Age(Date birthday, Date today) {
Calendar birthdayCalender = Calendar.getInstance()
birthdayCalender.setTime(birthday)
Calendar todayCalender = Calendar.getInstance()
todayCalender.setTime(today)
day = todayCalender.get(Calendar.DAY_OF_MONTH) - birthdayCalender.get(Calendar.DAY_OF_MONTH);
month = todayCalender.get(Calendar.MONTH) - birthdayCalender.get(Calendar.MONTH);
year = todayCalender.get(Calendar.YEAR) - birthdayCalender.get(Calendar.YEAR);
//按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。
if (day < 0) {
month -= 1;
todayCalender.add(Calendar.MONTH, -1);//得到上一个月,用来得到上个月的天数。
day = day + todayCalender.getActualMaximum(Calendar.DAY_OF_MONTH);
}
if (month < 0) {
month = (month + 12) % 12;
year--;
}
if (year > 0) {
age = year
unit = AgeUnit.YearOfAge
} else if (month > 0) {
age = month
unit = AgeUnit.MonthOfAge
} else {
age = day
unit = AgeUnit.DayOfAge
}
}

public String display() {
return age + unit
}

public String toString() {
return "Age{" +
"age=" + age +
", unit=" + unit +
", year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}

enum AgeUnit {
YearOfAge("岁"),
MonthOfAge("个月"),
DayOfAge("天");

private String symbol;

AgeUnit(String symbol) {
this.symbol = symbol;
}

public String getSymbol() {
return symbol;
}

@Override
public String toString() {
return symbol;
}

public static AgeUnit getUnitBySymbol(String val) {
val = val.trim().toLowerCase();
if ("岁".equals(val)) return YearOfAge;
else if ("个月".equals(val)) return MonthOfAge;
else if ("月".equals(val)) return MonthOfAge;
else if ("天".equals(val)) return DayOfAge;
throw new IllegalArgumentException(val + "不是合法的年龄单位");
}
}

class AgeTest extends GroovyTestCase {
def testAge() {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2008-07-01")
Date today = new SimpleDateFormat("yyyy-MM-dd").parse("2011-07-01")
def age = new Age(date, today)
println age
// Age{age=3, unit=岁, year=3, month=0, day=0}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: