【Java】根据生日计算年龄

方式一:时间戳速算
只适用于计算1970-01-01 08:00:00及之后出生的

// 1971-01-01 08:00:00的时间戳
private static final long TIME = 31536_000_000L;
public Integer getAge(Long birth) {
	if (birth == null) {
		return null;
	}
	
	Long now = System.currentTimeMillis();
	if (birth > now) {
		return 0;
	}
	
	if (birth > 0) {
		Double age = Math.ceil((now - birth) / TIME);
		return age.intValue();
	}
	return null;
}

方式二:年月日计算

public int getAge(Date birth) {
	Calendar cal = Calendar.getInstance();
	int thisYear = cal.get(Calendar.YEAR);
	int thisMonth = cal.get(Calendar.MONTH);
	int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
	
	cal.setTime(birth);
	int birthYear = cal.get(Calendar.YEAR);
	int birthMonth = cal.get(Calendar.MONTH);
	int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

	int age = thisYear - birthYear;

	// 未足月
	if (thisMonth <= birthMonth) {
		// 当月
		if (thisMonth == birthMonth) {
			// 未足日
			if (dayOfMonth < birthdayOfMonth) {
				age--;
			}
		} else {
			age--;
		}
	}
	return age;
}
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值