java计算年龄_Java根据出⽣⽇期计算年龄1.把出⽣⽇期字符串转换为⽇期格式。
public static Date parse(String strDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(strDate);
}
2.计算年龄
public static int getAge(Date birthDay) throws Exception {
Calendar cal = Instance();
if (cal.before(birthDay)) { //出⽣⽇期晚于当前时间,⽆法计算
throw new IllegalArgumentException(
"The birthDay is before Now.It's unbelievable!");
}
int yearNow = (Calendar.YEAR); //当前年份
int monthNow = (Calendar.MONTH); //当前⽉份
int dayOfMonthNow = (Calendar.DAY_OF_MONTH); //当前⽇期
cal.setTime(birthDay);
java时间日期格式转换int yearBirth = (Calendar.YEAR);
int monthBirth = (Calendar.MONTH);
int dayOfMonthBirth = (Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth; //计算整岁数
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth) age--;//当前⽇期在⽣⽇之前,年龄减⼀
}else{
age--;//当前⽉份在⽣⽇之前,年龄减⼀
} } return age; }
3.执⾏⽅法
public static void main(String[] args) {
try {
int age = getAge(parse("1990-09-27")); //由出⽣⽇期获得年龄***
System.out.println("age:"+age);
} catch (Exception e) {
e.printStackTrace();
} }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论