2013-08-22 65 views
0

我有一个Date。现在我想计算一下,如果条件成立,年龄应该是2-12岁,否则年龄应该在0-2岁之间。那么我们怎么能够计算一个特定日期的年龄是在2-12还是0-2之间。Java中的日期范围

我做了一些事情,但我很困惑,我该怎么做。

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

如果你想找到你所需要两个日期值的年龄。你可以尝试这样的事情

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"); 
    } 
3

你可以使用约达时间PeriodDocs

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 
} 
+0

基本上我有检查儿童和婴儿年龄的谎言2-12yrs和0-2岁之间同时 – Developer

+0

我很抱歉,我很困惑你的意思。你有什么机会可以更清楚你想要做什么? (也许编辑Q会更清楚?) – Stewart

+0

更新我的问题 – Developer