java根据出生日期计算年龄

本文提供了一种使用Java计算从出生日期到当前日期年龄的方法。通过解析字符串格式的日期,并利用Calendar类比较出生年份与当前年份来计算年龄。同时考虑了出生日期在当年是否已经到来的因素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      /**
* @param args
*/
public static void main(String[] args) {
System.out.print(getAge("2013-01-06"));
}

public static int getAge(String strBorthDay) {
int age=0;
try {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
Date borthDay=myFormatter.parse(strBorthDay);
Calendar born = Calendar.getInstance();
Calendar now = Calendar.getInstance();
if (borthDay != null) {
   now.setTime(new Date());
   born.setTime(borthDay);
   if (born.after(now)) {
       throw new IllegalArgumentException("年龄不能超过当前日期");
   }
   age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
   int nowDayOfYear = now.get(Calendar.DAY_OF_YEAR);
   int bornDayOfYear = born.get(Calendar.DAY_OF_YEAR);
   if (nowDayOfYear < bornDayOfYear) {
       age -= 1;
   }
}
} catch (ParseException e) {
e.printStackTrace();
return age;
}
        return age;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值