通过出生日期计算年龄,(birthday 为String ,length =10)有更简便的吗?

子非鱼的博客 2018-06-07 09:25:27
package com.cdu.dj.age;

import java.util.Calendar;

public class AgeUtil {

public static int age(String birthday){
//截取学生出生日期
String [] str = birthday.split("-");
int sYear = Integer.parseInt(str[0]);
int sMonth = Integer.parseInt(str[1]);
int sDay = Integer.parseInt(str[2]);
//获取当前年月日
Calendar cal = Calendar.getInstance();
int nowYear = cal.get(Calendar.YEAR);
int nowMonth = cal.get(Calendar.MONTH)+1;
int nowDay = cal.get(Calendar.DATE);

//当期-出生
int year = nowYear - sYear;
int month = nowMonth - sMonth;
int day = nowDay -sDay;

int age = year; // 大致赋值
if (year < 0) {// 选了未来的年份
age = 0;
} else if (year == 0) {// 同年的,要么为1,要么为0
if (month < 0) {// 选了未来的月份
age = 0;
} else if (month == 0) {// 同月份的
if (day < 0) {// 选了未来的日期
age = 0;
} else if (day>= 0) {
age = 1;
}
} else if (month > 0) {
age = 1;
}
} else if (year > 0) {
if (month < 0) {// 当前月>生日月
} else if (month == 0) {// 同月份的,再根据日期计算年龄
if (day < 0) {
} else if (day >= 0) {
age = age + 1;
}
} else if (month > 0) {
age = age + 1;
}
}
return age;
}

}
...全文
941 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
stacksoverflow 2018-06-07
  • 打赏
  • 举报
回复
JDK1.8, 输入检查请自己添加。 代码如下: public static int age(String birthday){ String[] ymdArray = birthday.split("-"); LocalDate birthDate = LocalDate.of( Integer.parseInt(ymdArray[0]), Integer.parseInt(ymdArray[1]), Integer.parseInt(ymdArray[2])); int age = Period.between(birthDate, LocalDate.now()).getYears(); return age < 0 ? 0 : age; }

50,639

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧