简体   繁体   中英

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 test 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="" , ie 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM