根据出生年月日计算出生了多少年,多少月,多少天
1,定义一个方法获得出生日期的Date类型时间
public static Date getDateFormat(String birthday) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parse = simpleDateFormat.parse(birthday);
return parse;
}
2,根据出生的时间Date和当前时间Date来计算出生了多少年,多少月,多少天
public static void getAge(String birthday) throws ParseException {
Date dateFormat = getDateFormat(birthday);
long birTime = dateFormat.getTime();
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
long nowTime = date.getTime();
if (nowTime < birTime) {
throw new IllegalArgumentException(
"对比的出生时间晚于当前的时间,无法进行比较!"
);
}
int nowYear = calendar.get(Calendar.YEAR);
int nowMon = calendar.get(Calendar.MONDAY) + 1;
int nowDay = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("当前 年 月 日:"+nowYear + " " + nowMon + " " + nowDay);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(dateFormat);
int birYear = calendar2.get(Calendar.YEAR);
int birMon = calendar2.get(Calendar.MONDAY) + 1;
int birDay = calendar2.get(Calendar.DAY_OF_MONTH);
System.out.println("出生时的年 月 日:"+birYear + " " + birMon + " " + birDay);
int age = nowYear - birYear;
int mon = 0;
int day = 0;
if (nowMon >= birMon) {
mon = nowMon - birMon;
if (nowDay >= birDay) {
day = nowDay - birDay;
} else {
mon = mon - 1;
day = birDay - nowDay;
int maximum = calendar.getActualMaximum(Calendar.DATE);
day = maximum - day;
}
} else {
age = age - 1;
mon = 12 - (birMon - nowMon);
if (nowDay >= birDay) {
day = nowDay - birDay;
} else {
mon = mon - 1;
day = birDay - nowDay;
int maximum = calendar.getActualMaximum(Calendar.DATE);
day = maximum - day;
}
}
System.out.println("出生日期:" + birYear + " " + birMon + " " + birDay);
System.out.println(age + "岁 " + mon + "月 " + day + "天");
}
测试
public static void main(String[] args) throws ParseException {
String birthday = "2000-9-31";
getAge(birthday);
}