1、获取系统时间计算年龄

public static int getAgeByBirthday(Date birthday) {
Calendar cal = Calendar.getInstance();
if (cal.before(birthday)) {
throw new IllegalArgumentException(
"The birthDay is before Now.It's unbelievable!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthday);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH) + 1;
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
// monthNow==monthBirth 
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
}
} else {
// monthNow>monthBirth 
age--;
}
}
return age;
}



2、输入时间参数计算年龄

public static int getAgeByBirthday(Date birthday, Date treattime) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(treattime);
if (cal1.before(birthday)) {
throw new IllegalArgumentException(
"The birthDay is before Now.It's unbelievable!");
}
int yearNow = cal1.get(Calendar.YEAR);
int monthNow = cal1.get(Calendar.MONTH) + 1;
int dayOfMonthNow = cal1.get(Calendar.DAY_OF_MONTH);

Calendar cal2 = Calendar.getInstance();
cal2.setTime(birthday);
int yearBirth = cal2.get(Calendar.YEAR);
int monthBirth = cal2.get(Calendar.MONTH) + 1;
int dayOfMonthBirth = cal2.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
// monthNow==monthBirth 
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
}
} else {
// monthNow>monthBirth 
age--;
}
}
return age;
}



发布评论
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

jqgrid 动态设置单元格不可编辑讲解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。