1 public static int getAge(Date birthDay) throws Exception { 2 Calendar cal = Calendar.getInstance(); 3 4 if (cal.before(birthDay)) { 5 throw new IllegalArgumentException( 6 "The birthDay is before Now.It‘s unbelievable!"); 7 } 8 9 int yearNow = cal.get(Calendar.YEAR); 10 int monthNow = cal.get(Calendar.MONTH); 11 int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); 12 cal.setTime(birthDay); 13 14 int yearBirth = cal.get(Calendar.YEAR); 15 int monthBirth = cal.get(Calendar.MONTH); 16 int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); 17 18 int age = yearNow - yearBirth; 19 20 if (monthNow <= monthBirth) { 21 if (monthNow == monthBirth) { 22 //monthNow==monthBirth 23 if (dayOfMonthNow < dayOfMonthBirth) { 24 age--; 25 } else { 26 //do nothing 27 } 28 } else { 29 //monthNow>monthBirth 30 age--; 31 } 32 } else { 33 //monthNow<monthBirth 34 //donothing 35 } 36 37 return age; 38 }
转载: http://www.blogjava.net/iamtin/archive/2006/03/10/34608.html
时间: 2024-10-07 17:31:44