如何创建一个计算来从两个日期中得出一个人的年龄?

我正在尝试一种方法来计算一个人的年龄。我希望计算在第二个下完成publicstaticint

getAge。如果该人在当前日期之后出生,我希望它显示错误-1。

我该如何比较这两个SimpleDatedateBddateRef获得年龄的整数值?

public static SimpleDate today() {

Calendar todayCal = Calendar.getInstance();

SimpleDate todayDate = new SimpleDate();

todayDate.setDate(todayCal.get(Calendar.MONTH) + 1,

todayCal.get(Calendar.DATE),

todayCal.get(Calendar.YEAR));

return todayDate;

public static int getAge(SimpleDate dateBd) {

int age;

SimpleDate dateToday = today();

age = getAge(dateBd, dateToday);

return age;

public static int getAge(SimpleDate dateBd, SimpleDate dateRef) {

if(getAge(dateBd)>getAge(dateRef)){

system.out.println("error");

}

return -1;

回答:

什么是SimpleDate?无论如何,这可以帮助您入门

 import java.util.GregorianCalendar;

import java.util.Calendar;

public class CalcAge {

public static void main(String [] args) {

// remember ... months are 0-based : jan=0 feb=1 ...

System.out.println

("1962-11-11 : " + age(1962,10,11));

System.out.println

("1999-12-03 : " + age(1999,11,3));

}

private static int age(int y, int m, int d) {

Calendar cal = new GregorianCalendar(y, m, d);

Calendar now = new GregorianCalendar();

int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);

if((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))

|| (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)

&& cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))

{

res--;

}

return res;

}

}

以上是 如何创建一个计算来从两个日期中得出一个人的年龄? 的全部内容, 来源链接: utcz.com/qa/422673.html

回到顶部