簡體   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