根据生日计算年龄
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;
}
}
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;
}
}
相关文章推荐
- sql 语句 根据顾客生日计算 顾客年龄
- MySQL根据生日计算年龄
- js根据生日计算出年龄
- mysql 年龄计算(根据生日)
- 根据生日计算年龄
- SPSS根据生日计算年龄并分组
- 根据生日计算年龄
- php根据生日计算年龄的方法
- javascript根据生日计算年龄
- IOS中根据生日精确计算年龄
- 问题:oracle 计算年龄;结果:oracle中根据生日计算年龄的问题
- javascript根据生日计算年龄
- java 根据生日计算年龄 Java问题通用解决代码
- java根据用户生日计算年龄
- php几种根据生日计算年龄的方法
- 新手学习:根据生日计算当前年龄
- 根据生日计算年龄
- mysql 年龄计算(根据生日字段)
- 根据生日计算年龄
- 根据用户生日计算年龄