有了这个实现似乎工作:
package net.orique.stackoverflow.question11740273;
import java.text.DateFormat;
import org.springframework.beans.propertyeditors.CustomDateEditor;
public class NotLenientDateEditor extends CustomDateEditor {
public NotLenientDateEditor(DateFormat dateFormat, boolean allowEmpty,
int exactDateLength) {
super(dateFormat, allowEmpty, exactDateLength);
dateFormat.setLenient(false);
}
}
类与main
方法:
package net.orique.stackoverflow.question11740273;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd.m.yy");
NotLenientDateEditor n = new NotLenientDateEditor(sdf, false, 7);
n.setAsText("12.1.20"); // Ok
n.setAsText("12.1.20asa21"); // Throws java.lang.IllegalArgumentException
}
}
笔记:
你如何实例化NotLenientDateEditor
?您为 DateFormat 设置了哪种格式?请注意构造函数参数的month
和7
的单个数字。exactDateLength