import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/** 将出生年月日按当前日期值(如:19890921)转化为年龄 */
@SuppressLint("SimpleDateFormat")
public int getAge(String brithday)
{
int age = 0;
try
{
// 对输入的生日格式 规整化为8位字符串形式
brithday = brithday.trim().replace("-", "").replace(" ", "").replace("_", "").replace("/", "").replace("\\", "").substring(0, 8);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date birthDay = format.parse(brithday);
long birthL = birthDay.getTime(); // 生日对应的毫秒时间值
Date now = new Date();
long nowL = now.getTime(); // 当前日期对应的毫秒时间值
if(nowL > birthL) age = (int) ((nowL - birthL) / 1000 / 60 / 60 / 24 / 365); // 时间差转化为年取整
}
catch (ParseException e)
{
e.printStackTrace();
}
return age;
}