根據生年月計算年齡 小方法

package test;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class test01 {


@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
// TODO 自動生成されたメソッド・スタブ
Date dbDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


dbDate = (Date) dateFormat.parse("1990-05-08");


System.out.println(getAge(dbDate));


}


public static int getAge(Date dateOfBirth) {
int age = 0;
Calendar born = Calendar.getInstance();
Calendar now = Calendar.getInstance();
if (dateOfBirth != null) {
now.setTime(new Date());
born.setTime(dateOfBirth);
if (born.after(now)) {
throw new IllegalArgumentException(
"Can't be born in the future");
}
age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
age -= 1;
}
}
return age;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章