zjh
2025-01-06 1ce606a5cd06b859a57eabf8b12c4fb3704168b4
ltkj-common/src/main/java/com/ltkj/common/utils/DateUtils.java
@@ -3,11 +3,8 @@
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
@@ -162,4 +159,52 @@
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
    /**
     * 根据日期获取 星期
     * @param
     * @return
     */
    public static String dateToWeek(Date date) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //一周的第几天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
    /**
     * 根据生日计算年龄值以及年龄单位
     * @param birthday 生日
     * @return
     */
    public static AgeResult calculateAge(Date birthday){
        LocalDate currentDate = LocalDate.now();
        LocalDate birthLocalDate = birthday.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        Period period = Period.between(birthLocalDate, currentDate);
        if (period.getYears() > 0){
            return new AgeResult(period.getYears(),1);
        }
        if (period.getMonths() > 0){
            return new AgeResult(period.getMonths(),2);
        }
        LocalDateTime birthDateTime = birthday.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime currentDateTime = LocalDateTime.now();
        Duration duration = Duration.between(birthDateTime, currentDateTime);
        long days = duration.toDays();
        if (days > 0){
            return new AgeResult((int) days,3);
        }
        long hours = duration.toHours();
        if (hours > 0){
            return new AgeResult((int) hours,4);
        }
        long minutes = duration.toMinutes();
        return new AgeResult((int) minutes,5);
    }
}