luodangjia
2024-12-10 ee7ce5d1cbf80bee0a15c1e5bc5eaa30858d812b
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
package com.hollywood.applet.utils;
 
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.concurrent.TimeUnit;
 
public class AgeCalculator {
 
    /**
     * Calculate the age based on the given birthdate which is a java.util.Date object.
     *
     * @param birthdate The birthdate as a java.util.Date object.
     * @return The age in years.
     */
    public static int calculateAge(Date birthdate) {
        // Convert java.util.Date to LocalDate
        LocalDate birthdateLocalDate = birthdate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
 
        // Get the current date
        LocalDate currentDate = LocalDate.now();
 
        // Calculate the age using Period
        Period agePeriod = Period.between(birthdateLocalDate, currentDate);
 
        // Return the age in years
        return agePeriod.getYears();
    }
 
 
}