liusheng
2 天以前 e842ed74b3167075e4f8f0cf76b38ddc53a8fb54
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.ruoyi.project.common;
 
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
 
public class CalculateDateUtils {
    public static Map<String, String> calculateAge(LocalDate birthdate, LocalDate today) {
        if (birthdate == null || today.isBefore(birthdate)) {
            return null;
        }
        Map<String, String> ageMap = new HashMap<>();
 
        Period period = Period.between(birthdate, today);
        long totalDays = ChronoUnit.DAYS.between(birthdate, today);
        long totalMonths = ChronoUnit.MONTHS.between(birthdate, today);
 
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();
 
        String ageUnit;
        Integer age;
        String ageUnit2 = null;
        Integer age2 = null;
 
        if (totalDays < 30) {
            // 小于 1 个月,按天计算
            ageUnit = "天";
            age = (int) totalDays;
            ageMap.put("age", age != null ? age.toString() : null);
            ageMap.put("ageUnit", ageUnit);
            ageMap.put("age2", null);
            ageMap.put("ageUnit2", null);
        } else if (totalMonths < 12) {
            // 小于 一年,按月 + 天计算
            ageUnit = "月";
            age = (int) totalMonths;
            ageUnit2 = "天";
            age2 = days;
            ageMap.put("age", age != null ? age.toString() : null);
            ageMap.put("ageUnit", ageUnit);
            ageMap.put("age2", age2 != null ? age2.toString() : null);
            ageMap.put("ageUnit2", ageUnit2);
        } else {
            // 大于等于 一年,按年 + 月计算
            ageUnit = "岁";
            age = years;
            ageUnit2 = "月";
            age2 = months;
            ageMap.put("age", age != null ? age.toString() : null);
            ageMap.put("ageUnit", ageUnit);
            ageMap.put("age2", age2 != null ? age2.toString() : null);
            ageMap.put("ageUnit2", ageUnit2);
        }
 
        return ageMap;
    }
}