[英]Why is Java telling me “” is a valid date?
So, this is what I'm using as my isDate
in Java.所以,这就是我在 Java 中使用的isDate
。
public class Common {
public static final String DATE_PATTERN = "yyyy-MM-dd";
public static boolean isDate(String text) {
return isDate(text, DATE_PATTERN);
}
public static boolean isDate(String text, String date_pattern) {
String newDate = text.replace("T00:00:00", "");
SimpleDateFormat formatter = new SimpleDateFormat(date_pattern);
ParsePosition position = new ParsePosition(0);
formatter.parse(newDate, position);
formatter.setLenient(false);
if (position.getIndex() != newDate.length()) {
return false;
} else {
return true;
}
}
}
Here is my test code:这是我的测试代码:
String fromDate = "";
if (Common.isDate(fromDate)) {
System.out.println("WHAT??????");
}
I see WHAT??????
我看到WHAT??????
printed every time.每次打印。 What am I missing here?我在这里想念什么?
Thanks.谢谢。
It is because your logic is not correct.那是因为你的逻辑不正确。 newDate=""
, ie newDate.length()==0
. newDate=""
,即newDate.length()==0
。 As well as position.getIndex()==0
since the error is occuring at the very beginning of the string.以及position.getIndex()==0
因为错误发生在字符串的最开头。 You may test whether position.getErrorIndex()>=0
.您可以测试position.getErrorIndex()>=0
是否。
The right way to check for a successful parse is to see, if the parse
method returns a Date or null
.检查成功解析的正确方法是查看parse
方法是否返回 Date 或null
。 Try this:尝试这个:
public static boolean isDate(String text, String date_pattern) {
String newDate = text.replace("T00:00:00", "");
SimpleDateFormat formatter = new SimpleDateFormat(date_pattern);
ParsePosition position = new ParsePosition(0);
formatter.setLenient(false);
return formatter.parse(newDate, position) != null;
}
Don't reinvent the wheel... use Joda Time ;)不要重新发明轮子……使用Joda Time ;)
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
try {
DateTime dt = fmt.parseDateTime("blub235asde");
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
}
return true;
Output: Output:
java.lang.IllegalArgumentException: Invalid format: "blub235asde"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:673)
at Test.main(Test.java:21)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.