2012-05-12 123 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