0

可能重复:
如何在 Java 中计算某人的年龄?

我正在 spring 框架中创建一个应用程序,该应用程序计算用户在 UI 中输入他们的出生日期后的年龄。到目前为止,我的 getAge bean 有获取和集合,但是我如何在语法上正确地计算方法?

import java.util.*;
public class ageBean {

Date birthdate;


public Date getBirthday(){
return birthdate;
}
 public void setBirthdate(Date birthdate){
this.birthdate=birthdate;
}

   //method goes here 
    }
4

3 回答 3

0

使用 java.util.Calendar 来确保闰年、月中不同的天数等被考虑在内,

int thisYear = Calendar.getInstance().get(Calendar.YEAR);
Calendar birthdateCalendar = Calendar.getInstance();
birthdateCalendar.setTime(birthdate);
int birthYear = birthdateCalendar.get(Calendar.YEAR);
int yearsSinceBirth = thisYear - birthYear;
于 2012-05-03T16:57:47.587 回答
0

您可以通过将 date1 替换为您的生日来尝试这段代码,

Date date= new Date(System.currentTimeMillis());
date.setYear(date.getYear()+1900);

// 这是因为 currentTimeMillis 返回从 1970 年 1 月 1 日起经过的时间

Date date1=new Date(2000,10,15);
long timegap =date.getTime()-date1.getTime();
long milliSecsInAYear = 31536000000L;

System.out.println(timegap/milliSecsInAYear+"years" +((date.getTime()-date1.getTime())%milliSecsInAYear)/(milliSecsInAYear/365)+"days" );

注意:我把一年当作有 365 天

于 2012-05-03T17:37:06.600 回答
0

Spring 什么都没有。如果要计算当前年龄,

    long diff = new Date().getTime() - birthdate.getTime(); // current date - b'day
    long diffSeconds = diff / 1000;         
    long diffMinutes = diff / (60 * 1000);         
    long diffHours = diff / (60 * 60 * 1000);                      
    System.out.println("Time in seconds: " + diffSeconds + " seconds.");         
    System.out.println("Time in minutes: " + diffMinutes + " minutes.");         
    System.out.println("Time in hours: " + diffHours + " hours."); 
于 2012-05-03T16:34:29.950 回答