提问者:小点点

如何使用Constructor中的出生日期计算年龄?


public class Application {
     public static void main(String[] args)  {

        StudentRepository myStudent = new StudentRepository();
    myStudent.addStudent("St","Rt","0742", "1993.03.04", PersonGender.MALE, "1930303");
    myStudent.addStudent("Sr","Ro","0742", "1994.03.04", PersonGender.MALE, "1940304");
    myStudent.addStudent("Se","Rb","0742", "1995.03.04", PersonGender.MALE, "1950305");
    myStudent.addStudent("Sm","Re","0742", "1996.03.04", PersonGender.MALE, "1950306");
    myStudent.deleteStudent("Stumer","Robert","0742", "1992.03.04", PersonGender.MALE, "null");
    myStudent.deleteStudent("Sr","Ro","0742", "1994.03.04", PersonGender.MALE, "1940304");
    myStudent.displayStudents();
    myStudent.calculateAge();// not working
 }
}


public static int calculateAge(Date birthDate) {
    /**      if ((birthDate != null) && (currentDate != null)) {
     return Period.between(birthDate, currentDate).getYears();
     } else {
     return 0;
     }*/
    int thisYear = Calendar.getInstance().get(Calendar.YEAR);
    Calendar birthdateCalendar = Calendar.getInstance();
    birthdateCalendar.setTime(birthDate);
    int birthYear = birthdateCalendar.get(Calendar.YEAR);
    int yearsSinceBirth = thisYear - birthYear;
    return  yearsSinceBirth;
}

日期代码是构造函数的第四个参数,在它下面是我为年龄计算实现的方法


共3个答案

匿名用户

int age = (new Date().getTime() - birthDate.getTime())/(1000 * 60*60 * 24*365):

匿名用户

好吧,如果您能够/允许使用java.time,那么您就可以在一个语句/仅仅几行中计算出一个人的年龄超过他/她的出生日期。

请参见此示例:

public static int getAgeInFullYears(LocalDate birthDate) {
    Period period = Period.between(birthDate, LocalDate.now());
    return period.getYears();
}

您必须将出生日期作为java.time.localdate的实例传递,您可以从之前的字符串(格式化为问题代码中的字符串)中解析该实例,请参见以下示例用法:

public static void main(String[] args) {
    // provide the date of birth as String
    String birthday = "1993.03.04";
    // parse it to a LocalDate using a formatter that parses the String format
    LocalDate birthDate = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy.MM.dd"));
    // then calculate the years using the method
    int ageInYears = getAgeInFullYears(birthDate);
    // and print some result statment
    System.out.printf("The person is %d years old (date of calculation %s)",
                    ageInYears,
                    LocalDate.now());
}

输出如下:

The person is 27 years old (date of calculation 2020-06-11)

匿名用户

您可以使用新的java.time类,它们更方便。

final LocalDate birth = birthDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
final LocalDate now = LocalDate.now();
final int age = Period.between(birth, now).getYears();