您的位置:首页 > 其它

根据生日计算年龄

2016-10-26 17:14 183 查看
package demo1;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;

public class getAge {
@Test
public void getAge(){
int age = getAge(new Date());
System.out.println(age);
}

public static int getAge(Date birthDate) {
if (birthDate == null)
throw new RuntimeException("出生日期不能为null");
int age = 0;
Date now = new Date();

SimpleDateFormat format_y = new SimpleDateFormat("yyyy");
SimpleDateFormat format_M = new SimpleDateFormat("MM");

String birth_year = format_y.format(birthDate);
String this_year = format_y.format(now);

String birth_month = format_M.format(birthDate);
String this_month = format_M.format(now);

// 初步,估算
age = Integer.parseInt(this_year) - Integer.parseInt(birth_year);

// 如果未到出生月份,则age - 1
if (this_month.compareTo(birth_month) < 0)
age -= 1;
if (age < 0)
age = 0;
return age;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: