Java 개발 팁 모음

프로젝트를 유지하면서 전임자들의 좋은 글쓰기 방법을 많이 접했고 여기에 기록하여 향후 개발을 위한 시간과 노력을 절약할 수 있습니다.

1. 나이 계산

테이블에 생년월일 필드가 있는 경우가 많지만 표시할 연령을 계산해야 하는 경우 클래스에서 중복 연령 필드를 사용한 다음 get 메서드에서 생년월일을 기준으로 연령 계산을 완료할 수 있습니다.

@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;
    }
}

나이를 계산하는 도구 클래스가 있습니다.

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. 자막

텍스트

在这里插入代码片

3. 자막

텍스트

在这里插入代码片

4. 자막

텍스트

在这里插入代码片

5. 자막

텍스트

在这里插入代码片

추천

출처blog.csdn.net/weixin_43487532/article/details/128326181