birthday为实体类当中的一个属性,通过改写set方法 计算年龄,如下图所示,
1:DateUtils.formatString(birthday.trim(),"yyyyMMdd") ,此方法为将传入的生日参数去除首位空格,后面为日期格式接着传入
DateUtils工具类的方法里
private String birthday;
public void setBirthday(String birthday) {
try{
this.birthday ="Y"+String.valueOf(DateUtils.getAge(DateUtils.formatString(
birthday.trim(),"yyyyMMdd")));
}catch( Exception e){
this.birthday ="";
}
}
方法如下: 需要两个参数 string类型,前者为生日日期,后者为日期格式
DateUtils. formatString(String date, String format);
/**
* 把字符串转换为DATE
*/
public static Date formatString(String date, String format) {
if (CommonUtil.isEmpty(date)) {
return null;
}
if (CommonUtil.isEmpty(format)) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat dateFormat = new SimpleDateFormat(format); // 格式化当前系统日期
Date newDate = new Date();
try {
newDate = dateFormat.parse(date);
} catch (Exception e) {
// e.printStackTrace();
}
return newDate;
}
通过转换字符串,返回的为Date类型的日期
DateUtils.getAge(Date birhtDay);此方法获取生日,如下:
// 根据日期获取生日
public static int getAge(Date birthDay) {
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) {
return 100;
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth)
age--;
} else {
age--;
}
}
return age;
}
得到生日,此时为int类型:
private String birthday;
public void setBirthday(String birthday) {
try{
this.birthday ="Y"+String.valueOf(DateUtils.getAge(DateUtils.formatString(
birthday.trim(),"yyyyMMdd")));
}catch( Exception e){
this.birthday ="";
}
}
通过String.valueOf(int) 方法将int转换为String类型的,
如此,在取值时即可直接得到生日大小