如何判断一个字符串为合法日期,字符串合法格式假设为"yyyy-mm-dd"SimpleDateFormat s = new SimpleDateFormat("yyyy-mm-dd");
s.parse("1986-07-1s8")//居然能通过 打印出来转换的日期成了1986年1月1日了。问题1:上述转换为什么啊?问题2:要解决这个问题还能采用其他的哪些方式呢?(集思广益)
s.parse("1986-07-1s8")//居然能通过 打印出来转换的日期成了1986年1月1日了。问题1:上述转换为什么啊?问题2:要解决这个问题还能采用其他的哪些方式呢?(集思广益)
(2)之所以是1月而不是7月,是因为mm代表分钟,MM才代表月份,所以你的格式应该是SimpleDateFormat("yyyy-MM-dd")问题2:
你可以自己预处理一下,用正则,或者自己判断一下字符串内容之类的都可以,取决于具体需要
总结下:
第一,首先要用正则来判断格式是否合法,排除类似这种的情况"1986-07-1s1",SimpleDateFormat会认为它通过的(详见3楼正解)
第二,SimpleDateFormat.setLenient(false);//小弟之前就不知道有这个方法,它是说需不需要严格的校验,不设置的话这种"1986-17-11"也会通过的.最后谢谢各位的热心帮助。虽然很简单,但是对于初出茅庐的童鞋们还是有用的。
2 (Simple)DateFormat的setLenient方法,设置为false
/**
* Specify whether or not date/time parsing is to be lenient. With
* lenient parsing, the parser may use heuristics to interpret inputs that
* do not precisely match this object's format. With strict parsing,
* inputs must match this object's format.
* @param lenient when true, parsing is lenient
* @see java.util.Calendar#setLenient
*/
2 setLenient(false)
/**
* Specify whether or not date/time parsing is to be lenient. With
* lenient parsing, the parser may use heuristics to interpret inputs that
* do not precisely match this object's format. With strict parsing,
* inputs must match this object's format.
* @param lenient when true, parsing is lenient
* @see java.util.Calendar#setLenient
*/