JAVA根据输入的出生日期转换成对应年龄

输入对应的出生日期,格式为yyyy-MM-dd,可以为2010,2010-01,2010-01-01格式

/**
	 * 根据出生年月计算年龄
	 * 
	 * @param birthday出生年月(可以为yyyy yyyy-MM yyyy-MM-dd)
	 * @return返回年龄
	 */
	public static Integer getAgeByBirthday(String birthday) {
		if ("".equals(birthday) || birthday == null) {
			return null;
		}
		// System.out.println("birthday>>>" + birthday);
		// 此处调用了获取当前日期,以yyyy-MM-dd格式返回的日期字符串方法
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowDate = sdf.format(new Date());

		String[] nowDates = nowDate.split("-");// 当前时间
		String[] dates = birthday.split("-");// 分割时间线 - 年[0],月[1],日[2]

		int age = Integer.parseInt(nowDates[0]) - Integer.parseInt(dates[0]);// 年龄默认为当前时间和生日相减

		if (dates.length >= 2) {// 根据月推算出年龄是否需要增加
			// 如果当前月份大于生日月份,岁数不变,否则加一
			Integer nowMonth = Integer.parseInt(nowDate.substring(5, 7));
			Integer birthMonth = Integer.parseInt(birthday.substring(5, 7));
			if (nowMonth < birthMonth)
				age++;
			if (dates.length >= 3 && nowMonth == birthMonth) {// 月份相同才计算对应年龄
				// 如果天数大于当前生日月份,岁数不变,否则加一
				Integer nowDay = Integer.parseInt(nowDates[2]);// 当前天数
				Integer birDay = Integer.parseInt(dates[2]);// 生日天数
				if (nowDay < birDay)
					age++;
			}

		}

		return age;
	}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值