因此,我想将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,但是没有运气。
转换程序将在页面上(在jsp / html页面中)以这种格式向您显示日期。它的作用是将日期转换为格式为dd-mm-yyyy的字符串。当您在validate函数中传递卡路里时,它不会以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 );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句