SimpleDateFormat严格限制日期转换setLenient(false)

来源:互联网 发布:mac隐藏dock快捷键 编辑:程序博客网 时间:2024/05/21 18:36
String text ="1996-2-1";

Date d = null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);//这个的功能是不把1996-13-3 转换为1997-1-3
try
{
d = df.parse(text);
}
catch(Exception e)
{
d=new Date();
System.out.println("你输入的日期不合法,请重新输入");
}
String sdata=df.format(d);
System.out.println(sdata);

这样输入1996-2-31这样的数据也会验证出来错误的,但是前提是要设置Lenient为false

原创粉丝点击