0

我有一个Date. 现在我想计算如果条件为真,则年龄为 2-12 岁,否则年龄应在 0-2 岁之间。那么我们如何计算给定日期的年龄是在 2-12 还是 0-2 之间。

我已经做了一些事情,但我很困惑我该如何继续。

public class Test {
  public static void main(String args[]) throws ParseException {
    String string = "29/07/13";
    Date oneWayTripDate = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
    String myFormat = "dd/MM/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);       
  }
}

然后条件将是这样的

for child age should be between 2-12 (So from Current Date will calulate to  12 yrs .if the date given lies between 2-12yrs then it is true otherwise false) 
for infant age should be between 0-12 (So from Current Date will calulate to  2 yrs .if the date given lies between 0-2yrs then it is true otherwise false)
4

2 回答 2

4

如果要查找年龄,则需要两个日期值。你可以试试这样的

    DateFormat df=new SimpleDateFormat("dd/MM/yy");
    Date birthDay=df.parse("29/07/13");
    Date currentDay=new Date();
    Calendar cal1=Calendar.getInstance();
    Calendar cal2=Calendar.getInstance();
    cal1.setTime(birthDay);
    cal2.setTime(currentDay);
    int years=cal2.get(Calendar.YEAR)-cal1.get(Calendar.YEAR);
    if(3>years){
        System.out.println("Infant");
    }else if(years<13){
        System.out.println("Child");
    } else{
        System.out.println("adult");
    }
于 2013-08-22T11:56:54.713 回答
3

您可以使用 Joda Time Period ( Docs )

Date tripDate;
Date dob;
Period period = new Period(dob, tripDate, PeriodType. YearMonthDay);
int years = period.getYears();
if(years < 3) {
    // 0 - 2
} else if(years < 13) {
    // 2 - 12
} else {
    // adult
}
于 2013-08-22T11:47:26.727 回答