根据出生年月日判断年龄

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*实现步骤:
1、获取当前时间
2、判断出生日期是否小于当前时间,如果大于,则引发异常
3、从当前时间中取出年、月、日;从出生日期中取出年、月、日,年份相减
4、然后做具体判断
*/
public class Main {
	public static void main(String[] args) {
		try {
			String str = "1993-8-22";
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			Date birthdate = formatter.parse(str);
			System.out.println(getAge(birthdate));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	public static int getAge(Date birthDay) throws Exception {
		// 获取当前系统时间
		Calendar cal = Calendar.getInstance();
		// 如果出生日期大于当前时间,则抛出异常
		if (cal.before(birthDay)) {
			throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
		}
		// 取出系统当前时间的年、月、日部分
		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH);
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

		// 将日期设置为出生日期
		cal.setTime(birthDay);
		// 取出出生日期的年、月、日部分
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH);
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
		// 当前年份与出生年份相减,初步计算年龄
		int age = yearNow - yearBirth;
		// 当前月份与出生日期的月份相比,如果月份小于出生月份,则年龄上减1,表示不满多少周岁
		if (monthNow <= monthBirth) {
			// 如果月份相等,在比较日期,如果当前日,小于出生日,也减1,表示不满多少周岁
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth)
					age--;
			} else {
				age--;
			}
		}
		System.out.println("age:" + age);
		return age;
	}
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhifanxu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值