2011-07-14 34 views
1

所以,這就是我在Java中使用的我的isDate爲什麼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; 
     } 
    } 
} 

這裏是我的測試代碼:

String fromDate = ""; 

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

我看到WHAT??????打印每次。我在這裏錯過了什麼?

謝謝。

+0

嘗試測試'position.getErrorIndex()!= - 1'。 http://download.oracle.com/javase/1.4.2/docs/api/java/text/ParsePosition.html#getErrorIndex%28%29 – JAB

回答

2

檢查成功解析的正確方法是查看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; 
} 
+0

這很好!謝謝 – cbmeeks

+1

請注意,對於諸如「2003-03-01sdfsdf」這樣的日期,這也會返回true(假設您沒有在第一行進行替換) – Kal

+0

好點。目前這在一個只接受一種日期的地方使用(這就是爲什麼我刪除了「T00 ...」)是否有更多的防彈方法? – cbmeeks

6

這是因爲你的邏輯不正確。 newDate="",即newDate.length()==0。以及position.getIndex()==0,因爲錯誤發生在字符串的一開始。你可以測試是否position.getErrorIndex()>=0

+0

+1 - 是這是實際的問題。 – CoolBeans

+0

感謝您解釋這 – cbmeeks

0

不要重新發明輪子...使用Joda Time;)

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

輸出:

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