温馨提示×

Java计算年龄的方法是什么

小亿
102
2024-06-06 16:30:20
栏目: 编程语言

要计算一个人的年龄,我们需要知道该人的出生日期和当前日期。以下是在Java中计算年龄的方法:

import java.time.LocalDate;
import java.time.Period;

public class AgeCalculator {
    
    public static int calculateAge(LocalDate birthDate) {
        LocalDate currentDate = LocalDate.now();
        Period period = Period.between(birthDate, currentDate);
        return period.getYears();
    }

    public static void main(String[] args) {
        LocalDate birthDate = LocalDate.of(1990, 5, 15); // 1990-05-15
        int age = calculateAge(birthDate);
        System.out.println("The age is: " + age);
    }
}

在上面的示例中,我们使用LocalDate类来表示生日和当前日期,然后使用Period类的between方法来计算两个日期之间的年龄差异。最后,我们通过getYears()方法获取年龄。

0