繁体   English   中英

为什么 Java 告诉我“”是有效日期?

[英]Why is Java telling me “” is a valid date?

所以,这就是我在 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;
        }
    }
}

这是我的测试代码:

String fromDate = "";

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

我看到WHAT?????? 每次打印。 我在这里想念什么?

谢谢。

那是因为你的逻辑不正确。 newDate="" ,即newDate.length()==0 以及position.getIndex()==0因为错误发生在字符串的最开头。 您可以测试position.getErrorIndex()>=0是否。

检查成功解析的正确方法是查看parse方法是否返回 Date 或null 尝试这个:

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;
}

不要重新发明轮子……使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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