puzhibing
2024-02-05 640ff18d2d7f4be02ddb7f8f75e899f05545eb98
cloud-server-other/src/main/java/com/dsh/other/util/DateUtil.java
@@ -150,7 +150,7 @@
     */
    public static Date parse(String date, String pattern) {
        try {
            if(Objects.nonNull(date)) {
            if (Objects.nonNull(date)) {
                return DateUtils.parseDate(date, pattern);
            }
        } catch (ParseException e) {
@@ -286,6 +286,7 @@
        Calendar cal = Calendar.getInstance();
        return cal;
    }
    /**
     * 毫秒转日期时间
     *
@@ -329,4 +330,42 @@
        return dt1.getTime();
    }
    /**
     * 计算年龄
     *
     * @param birthDate
     * @return
     */
    public static int age(Date birthDate) {
        // 当前日历
        Calendar nowCalendar = Calendar.getInstance();
        // 生日大于当前日期
        if (nowCalendar.before(birthDate)) {
            throw new IllegalArgumentException("The birth date is before current time, it's unbelievable");
        }
        // 当前年月日
        int yearNow = nowCalendar.get(Calendar.YEAR);
        int monthNow = nowCalendar.get(Calendar.MONTH);
        int dayNow = nowCalendar.get(Calendar.DAY_OF_MONTH);
        // 出生日期年月日
        Calendar birthCalendar = Calendar.getInstance();
        birthCalendar.setTime(birthDate);
        int yearBirth = birthCalendar.get(Calendar.YEAR);
        int monthBirth = birthCalendar.get(Calendar.MONTH);
        int dayBirth = birthCalendar.get(Calendar.DAY_OF_MONTH);
        // 粗计算年龄
        int age = yearNow - yearBirth;
        // 当前月份小于出生月份年龄减一
        if (monthNow < monthBirth) {
            age--;
        }
        // 当前月份等于出生月份,日小于生日年龄减一
        else if (monthNow == monthBirth && dayNow < dayBirth) {
            age--;
        }
        // 返回年龄值
        return age;
    }
}