2013-08-22 163 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