计算两个日期时间之间的差异

时间:2016-03-02 11:45:53

标签: jsf primefaces

我有两个主要日历组件如下:

<h:outputLabel value="#{prezmsg['MAINTENANCE.DATE_DEBUT']}"/>
<p:calendar id="dateDebut-create"
            value="#{maintenanceMBean.webBean.vo.dateDebut}"
            pattern="dd-MM-yyyy HH:mm:ss" mask="true">
    <p:ajax event="dateSelect" listener="#{maintenanceMBean.webBean.dateDiff}"/>
</p:calendar>
<p:message for="dateDebut-create"/>

<h:outputLabel value="#{prezmsg['MAINTENANCE.DATE_FIN']}"/>
<p:calendar id="dateFin-create"
            value="#{maintenanceMBean.webBean.vo.dateFin}" pattern="dd-MM-yyyy HH:mm:ss"
            mask="true">
    <p:ajax event="dateSelect" listener="#{maintenanceMBean.webBean.dateDiff}"/>
</p:calendar>
<p:message for="dateFin-create"/>

所以我想计算这两个日历组件之间的时间差异,并将该值放在另一个仅限时间的日历中。

<h:outputLabel value="#{prezmsg['MAINTENANCE.DUREE']}"/>
                <p:calendar id="duree-create" value="#{maintenanceMBean.webBean.vo.duree}" pattern="HH:mm:ss"
                            timeOnly="true" readonly="true"/>
                <p:message for="duree-create"/>

当我选择开始日期和结束日期时,会触发此功能:

public void dateDiff(SelectEvent event){
        if(getVo().getDateDebut() != null && getVo().getDateFin() != null){

            Date calculatedTime = null;
            long diff = getVo().getDateFin().getTime() - getVo().getDateDebut().getTime();
            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000);

            try {
                calculatedTime =  new SimpleDateFormat("HH:mm:ss").parse(diffHours+":"+diffMinutes+":"+diffSeconds);
                System.out.print("Calculated Time : " + calculatedTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            getVo().setDuree(calculatedTime);
        }
    }

所以在控制台中我有这样的消息:Calculated Time : Fri Jan 02 00:00:00 GMT 1970我没有设置第三个组件的值。

1 个答案:

答案 0 :(得分:0)

一旦计算出差异,您的Ajax事件需要update第三个日历组件:

<p:ajax event="dateSelect" 
listener="#{maintenanceMBean.webBean.dateDiff}" update="duree-create"/>