具有Calendar primefaces的Validator

时间:2015-11-15 13:05:57

标签: java datetime primefaces

查看:

<p:calendar id="dateRequisition" widgetVar="calwidget" pattern="yyyy-MM-dd HH:mm" value="#{examrequisitionsController.selected.dateRequisition}"
                                title="#{bundle.CreateExamrequisitionsTitle_dateRequisition}" required="true" requiredMessage="#{bundle.CreateExamrequisitionsRequiredMessage_dateRequisition}"
                                converterMessage="Invalid Birth Date." effect="slide" showOn="both" navigator="true" yearRange=":+1"
                                minHour="06" maxHour="18" stepMinute="10" disabledWeekends="true" readonlyInput="true">
    <f:validator validatorId="dateValidator" />
</p:calendar>

验证

public void validate(FacesContext context, UIComponent component,
        Object value) throws ValidatorException {
    String msg = "";
    if (value == null) {
        msg = "The Date field is required";
    } else {
        Date dateRequisition = null;
        try {
            dateRequisition = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH).parse(value.toString());

        } catch (ParseException ex) {
            Logger.getLogger(DateValidator.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (!Persistence.createEntityManagerFactory("SystemCardiologyReportsPU").createEntityManager().createNamedQuery("Examrequisitions.findByDateRequisition")
                .setParameter("dateRequisition", dateRequisition).getResultList().isEmpty()) {
            msg = "The Date of requisition is already defined.";
        }
    }
    if (!"".equals(msg)) {
        JsfUtil.validatorMessage(msg);
    }
}

DB中的列: dateRequisition datetime NOT NULL

我进行了调试,验证器类中收到的值采用以下格式:(java.util.Date) Sun Nov 15 06:00:00 GMT-03:00 2015

所以,我想将其格式化为yyyy-MM-dd HH:mm并与我的数据库中的所有日期进行比较,以测试它是否已包含在我的数据库中。

顺便说一下,它总是捕捉到ParseException。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案Date format parse exception - "EEE MMM dd HH:mm:ss Z yyyy"

dateRequisition = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH).parse(value.toString());