以下代码...
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
Date date = df.parse("2012115");
...将字符串 "2012115"
解析为相当于 2012 年 11 月 5 日的日期。我希望它解析失败,因为它缺少一天字符。换句话说,我只希望字符串 "20121105"
计算到该日期。除了评估字符串的长度之外,还有其他方法可以强制执行此操作吗?
最佳答案
...parses the string "2012115" to the Date equivalent of November 5th, 2012. I want it to fail parsing, because it is missing one day character. In other words, I only want the string "20121105" to evaluate to that date.
我怀疑您只能使用格式化程序来完成此操作。作为解决方法,您可能需要在解析之前检查日期字符串长度,如下所示:
String dateString = "2012115";
String formatString = "yyyyMMdd";
if(dateString == null || dateString.length() != formatString.length()){
throw new ParseException("Invalid Date Input", 0);
}
SimpleDateFormat formatter= new SimpleDateFormat(formatString);
formatter.setLenient(false);
Date date = df.parse(dateString);
关于java - 如何强制 dateFormat 将指定数量的字符视为有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520846/