【问题标题】:Formatting and validating a date in JSF在 JSF 中格式化和验证日期
【发布时间】:2014-07-25 09:10:21
【问题描述】:

所以我想将我的 dateinputfield 格式化为“dd-MM-yyyy”,然后验证日期不在明天之前。

这是我认为的相关代码:

   <h:inputText id="dueDate" required="true" value="#{submitRepairBean.dueDate}">
                <f:convertDateTime pattern="dd-MM-yyyy"/>   
                <f:validator validatorId="be.kdg.repaircafe.validators.DueDateValidator"/>
   </h:inputText>

这是我的自定义验证器:

@FacesValidator("be.kdg.repaircafe.validators.DueDateValidator")
public class DueDateValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        System.out.println(value.toString()); //For some reason this prints Wed Jul 23 02:00:00 CEST 2014 when inputting 23-07-2014
        DateTime date = new DateTime(value.toString());
        long dueDateMillis = date.getMillis();
        long oneDayMillis = 86400000;
        Calendar tomorrowMidnight = new GregorianCalendar();
        // reset hour, minutes, seconds and millis
        tomorrowMidnight.set(Calendar.HOUR_OF_DAY, 0);
        tomorrowMidnight.set(Calendar.MINUTE, 0);
        tomorrowMidnight.set(Calendar.SECOND, 0);
        tomorrowMidnight.set(Calendar.MILLISECOND, 0);
        tomorrowMidnight.add(Calendar.DAY_OF_MONTH, 1);
        if (dueDateMillis + oneDayMillis < tomorrowMidnight.getTimeInMillis()) {
            throw new ValidatorException(new FacesMessage("You can not have something repaired before tomorrow!"));
        }

    }

现在我不明白的是为什么它不以转换后的格式 (dd-MM-yyyy) 打印,即使这样我也不在乎,只要我得到正确的毫秒数。 但是,DateTime 构造函数随后会引发日期格式无效的异常。

我也尝试过使用 SimpleDateFormat,但没有成功。

【问题讨论】:

  • 尝试使用 Date date = (Date) value 转换您的值;到 java.util.Date 的日期对象,然后调用 new DateTime(date);
  • 您也可以使用一些更具代表性的 id 作为验证器ID,例如 dateValidator 或birthdayValidator
  • 仅供参考,麻烦的旧日期时间类,如 java.util.Date、java.util.Calendar 和 java.text.SimpleDateFormat 现在是 legacy,被 Java 8 和 Java 中内置的 java.time 类所取代9. 见Tutorial by Oracle。

标签: java validation jsf date datetime


【解决方案1】:

转换器它将在页面上(在 jsp/html 页面中)以这种格式显示日期。它的作用是将日期转换为 dd-mm-yyyy 格式的字符串。当您在 validate 函数中传递 calue 时,它​​不会转换为 dd-MM-yyyy 格式的字符串。它是一个日期,dueDate 是一个日期,所以通过打印 value.toString() 只是将日期值转换为字符串。所以对象是一个日期,只需转换为 Date 就可以了。如果你想在代码中以 dd-MM-yyyy 格式打印它,试试这个

Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String strDate = sdf.format(date);
System.out.println(strDate );

【讨论】:

    【解决方案2】:
    @FacesValidator("validator.dateValidator")
    public class DateValidator implements Validator, ClientValidator {
        final static String DATE_FORMAT = "dd-MM-yyyy";
        public DateValidator() {
        }
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            if (value == null || StringUtils.isEmpty((String) value.toString())) {
                return;
            }       
            SimpleDateFormat objDf = new SimpleDateFormat(DATE_FORMAT);
            objDf.setLenient(false);
    
            try {
                try {           
            Date data = new Date();
            data.setDate(data.getDate() + 1);
            if(objDf.parse(value.toString()).before(data)){
                ((UIInput) component).setValid(false);
                throw new ValidatorException(new FacesMessage("You can not have something repaired before tomorrow!"));
            }
        } catch (ParseException e) {
    
            ((UIInput) component).setValid(false);
            throw new ValidatorException(new FacesMessage(MessageUtils.ALERTA, "Data informada não Válida!", ""));
    
        }       
            } catch (ParseException e) {            
                 throw new ValidatorException(new FacesMessage("Invalid Date!"));
            }
        }
        public Map<String, Object> getMetadata() {
            return null;
        }
        public String getValidatorId() {
            return "validator.dateValidator";
        }
    }
    

    【讨论】:

    • 在 Stackoverflow 中为答案添加文字解释是一种很好的常见做法。如果你不这样做,你就有机会被否决并关闭。
    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 2010-11-22
    • 2011-01-06
    • 1970-01-01
    相关资源
    最近更新 更多