2012-05-12 173 views
0

我有一個表格,我使用pimefaces日曆組件,現在當用戶使用此組件選擇他的出生日期時,我想計算他的當前年齡和需要放入一個文本框。年齡文本框應該會自動顯示,因爲用戶將選擇他的出生日期。從出生日期(使用日曆)計算年齡IN Jsf

<h:outputLabel for="dobirth" value="Date of Birth (mu)" /> 
       <p:calendar value="#{patient.dob}" id="popupCal"> 
<p:ajax event="dateSelect" listener="#{patient.handleDateSelect}" /> 
       </p:calendar> 

我想通過這種方式來計算年齡。

public void handleDateSelect(DateSelectEvent event) throws ParseException { 

     System.out.println("inside get age"); 
     FacesContext facesContext = FacesContext.getCurrentInstance(); 
     SimpleDateFormat format = new SimpleDateFormat("d/M/yyyy"); 
     facesContext.addMessage(null, 
       new FacesMessage(FacesMessage.SEVERITY_INFO, "Date Selected", 
         format.format(event.getDate()))); 
     String dd=null; 
     dd=format.format(event.getDate()); 
     System.out.println("date dd"+dd); 
     Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(dd); 
     System.out.println("date+++++++++"+date); 
     Calendar birth = new GregorianCalendar(); 
     Calendar today = new GregorianCalendar(); 
     int calculatedAge = 0; 
     int factor = 0; 

     Date currentDate = new Date(); // current date 
     System.out.println("DOB" + dob); 
     birth.setTime(date); 
     System.out.println("set birth" + birth); 
     today.setTime(currentDate); 

     if (today.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)) { 
      factor = -1; 

     } 
     calculatedAge = today.get(Calendar.YEAR) - birth.get(Calendar.YEAR) 
       + factor; 
     System.out.println("age is " + calculatedAge); 
    } 

而且我還需要在用戶使用日曆選擇他的出生時立即顯示年齡。

一旦我達到了我的年齡,我如何在jsf 2.0中顯示它?

回答

3

像這樣的東西(添加到calculatedAge財產)。

<h:form> 
    <h:outputLabel for="dobirth" value="Date of Birth (mu)" /> 
    <p:calendar value="#{patient.dob}" id="popupCal"> 
     <p:ajax event="dateSelect" listener="#{patient.handleDateSelect}"  
       update="age" /> 
     </p:calendar> 
    <h:outputText id="age" value="#{patient.calculatedAge}"/> 
</h:form> 
+0

如果'update'中的表單ID已經在同一個表單中,那麼無需在'update'中加上前綴,這樣'prependId =「false」'在這裏沒有值。 – BalusC

+0

@BalusC是的,它只是我的習慣... :)編輯... – Daniel

+0

這並不重要,但我的意思是說,當你不使用'prependId =「時,你推薦使用'update =」:formID:age「'假「」是錯誤的。 – BalusC