根据生日计算年龄(精确到日与判断闰年)
具体代码
package com.test.UserBirthday4Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 根据生日计算出年龄,精确到天(含闰年情况)。
*/
public class DateInfo {
// 如果当前时间是2012-2-29 那么,today.getMonth()的值是一。
public int userBirthdayGetAge(String birthday) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd");
String mDateTime = formatter.format(cal.getTime());// 当前时间
java.util.Date today = formatter.parse(mDateTime);
java.text.SimpleDateFormat sdf =new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date birday = sdf.parse(birthday);// 当前对当前的情况
int age = today.getYear() - birday.getYear();
if (today.getMonth() == birday.getMonth()
&&today.getDate() ==birday.getDate()
&&birday.getYear() % 4 != 0 &&today.getYear() != 0
&&birday.getMonth() != 1 &&today.getMonth() != 1) {// 月份和日期都与当前时间相同(除去生日和当前年是闰年,并且是二月的情况)
return age;
} else if (today.getMonth() < birday.getMonth()) {// 生日的月份大于当前时间的月份
return age - 1;
} else if (birday.getMonth() == 1 && birday.getDate() == 29// 生日是闰年,当前年不一定是闰年
&&today.getMonth() == 1) {// 生日是闰年的情况,并且本月是二月
if (today.getYear() % 4 == 0) {// 当前年是闰年 2月有二十九
if (today.getDate() <birday.getDate()) {//
return age - 1;
}else {
return age;
}
}else {// 当前是年二月是二十八天
if (today.getDate() <birday.getDate() - 1) {
return age - 1;
}else {
return age;
}
}
} else if (today.getMonth() == 1 && today.getDate() == 29 && birday.getMonth() == 1) { // 当前年是闰年,生日年不一定是闰年
if (birday.getYear() % 4 == 0) {// 生日年是闰年 二月有二十九天
if (today.getDate() <birday.getDate()) {//
return age - 1;
}else {
return age;
}
}else {// 生日年二月是二十八天
if (today.getDate() + 1 <birday.getDate()) {
return age - 1;
}else {
return age;
}
}
} else if (today.getMonth() > birday.getMonth()) {// 不是同一年,生日的月份不大于当前的月份的情况
return age;
} else if (today.getDate() < birday.getDate()) {// 正常的日期(非闰年) 当前 小于 出生
return age - 1;
} else if (today.getDate() == birday.getDate()) {// 当前 等于 出生
return age;
} else {
return age; // 当前 大于 出生
}
}
}
闰年规律
// 规律,闰年%4结果为0
// numYear%4
// rn.test(2012); 0
// rn.test(2013); 1
// rn.test(2014); 2
// rn.test(2015); 3
// rn.test(2016); 0
调用与测试举例
public static void main(String[] args) {
DateInfo at =new DateInfo();
try {
int age = at.userBirthdayGetAge("1989-06-23");
System.out.println(age);
} catch (ParseException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}