【问题标题】:Calculate age from date of birth(using calender) IN Jsf从出生日期计算年龄(使用日历)IN Jsf
【发布时间】:2012-05-12 11:32:38
【问题描述】:

我有一个使用 pimefaces 日历组件的表单,现在当用户使用此组件选择他的出生日期时,我想计算他的当前年龄并需要放入一个文本框。当用户选择他的出生日期时,年龄文本框应该会自动显示。

<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 中显示它?

【问题讨论】:

    标签: jsf-2 primefaces


    【解决方案1】:

    类似这样的东西(将 getter 添加到 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>
    

    【讨论】:

    • 如果update中的表单ID已经在同一个表单中,则不需要在表单ID前面加上前缀,因此prependId="false"在这里没有任何价值。
    • 没关系,但我的意思是你建议在不使用prependId="false"时使用update=":formID:age"是错误的。
    • @BalusC 好吧,实际上我的意思是,如果 update="age" 找不到元素,他将需要检查年龄 id 是否被某个容器预先设置...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多