开发者

Why is Java telling me "" is a valid date?

So, this is what I'm using as my isDate in Java.

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 te开发者_如何学运维st code:

String fromDate = "";

if (Common.isDate(fromDate)) {
    System.out.println("WHAT??????");
}

I see WHAT?????? printed every time. What am I missing here?

Thanks.


It is because your logic is not correct. newDate="", i.e. newDate.length()==0. As well as position.getIndex()==0 since the error is occuring at the very beginning of the string. You may test whether position.getErrorIndex()>=0.


The right way to check for a successful parse is to see, if the parse method returns a Date or 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 ;)

    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
    try {
        DateTime dt = fmt.parseDateTime("blub235asde");
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return false;
    }
    return true;

Output:

java.lang.IllegalArgumentException: Invalid format: "blub235asde"
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:673)
    at Test.main(Test.java:21)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜