如何创建计算以从两个日期获取一个人的年龄?

How can I create a calculation to get the age of a person from two dates?

我正在尝试制作一种可以计算一个人年龄的方法。我想在第二个publicstaticintgetAge下进行计算。如果此人出生在当前日期之后,我希望它打印出错误 -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;

什么是简单日期?不管怎样,这里有一些东西可以让你开始

 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;
   }
} 

永远不要尝试使用两次之间的毫秒差来计算差异,date/time 计算有很多特质,可能会导致各种错误。

相反,为自己节省(很多)时间并使用专用库

Java 8

LocalDate start = LocalDate.of(1972, Month.MARCH, 8);
LocalDate end = LocalDate.now();

long years = ChronoUnit.YEARS.between(start, end);
System.out.println(years);

输出43

JodaTime

DateTime startDate = new DateTime(1972, DateTimeConstants.MARCH, 8, 0, 0);
DateTime endDate = new DateTime();

Years y = Years.yearsBetween(startDate, endDate);
int years = y.getYears();
System.out.println(years );

输出43

您甚至可以使用 Period 来获得更多粒度...

    Period period = new Period(startDate, endDate);
    PeriodFormatter hms = new PeriodFormatterBuilder()
                    .printZeroAlways()
                    .appendYears()
                    .appendSeparator(" years, ")
                    .appendMonths()
                    .appendSeparator(" months, ")
                    .appendDays()
                    .appendLiteral(" days")
                    .toFormatter();
    String result = hms.print(period);
    System.out.println(result);

打印 43 years, 1 months, 5 days