When maintaining the project, I encountered a lot of good writing methods from the predecessors. Record them here to save time and effort for future development.
1. Calculate age
Many times the table has a date of birth field, but when we need to calculate their age for display, we can use a redundant age field in the class, and then complete the age calculation based on the date of birth in the get method.
@Data
@TableName("sys_user")
public class SysUser{
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.UUID)
private String id;
/**
* 头像
*/
@TableField("AVATAR")
private String avatar;
/**
* 账号
*/
@TableField(name = "ACCOUNT",)
private String account;
/**
* 密码
*/
@TableField("PASSWORD")
private String password;
/**
* 出生日期
*/
@TableField("BIRTHDAY")
private String birthday;
/**
* 年龄
*/
@TableField(exist = false)
private int age;
public int getAge() {
//这个就是为空判断
if (ToolUtil.isNotEmpty(birthday)) {
return DateTimeKit.ageOfNow(birthday);
}
return age;
}
}
There is a tool class for calculating age
public class DateTimeKit {
/**
* 生日转为年龄,计算法定年龄
* @param birthDay 生日
* @return 年龄
* @throws Exception
*/
public static int ageOfNow(Date birthDay) {
return age(birthDay,date());
}
/**
* 计算相对于dateToCompare的年龄,长用于计算指定生日在某年的年龄
* @param birthDay 生日
* @param dateToCompare 需要对比的日期
* @return 年龄
* @throws Exception
*/
public static int age(Date birthDay, Date dateToCompare) {
Calendar cal = Calendar.getInstance();
cal.setTime(dateToCompare);
if (cal.before(birthDay)) {
throw new IllegalArgumentException(StrKit.format("Birthday is after date {}!", formatDate(dateToCompare)));
}
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);
int age = year - cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
if (month == monthBirth) {
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
if (dayOfMonth < dayOfMonthBirth) {
//如果生日在当月,但是未达到生日当天的日期,年龄减一
age--;
}
} else if (month < monthBirth){
//如果当前月份未达到生日的月份,年龄计算减一
age--;
}
return age;
}
}
2. Subtitles
text
在这里插入代码片
3. Subtitles
text
在这里插入代码片
4. Subtitles
text
在这里插入代码片
5. Subtitles
text
在这里插入代码片