我想解析一個日期字符串,可以有樹不同的格式。 儘管字符串不應該匹配第二個模式,但它會以某種方式執行,因此會返回錯誤的日期。SimpleDateFormat.parse()忽略模式中的字符數
這是我的代碼:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Start {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
try{
System.out.println(sdf.format(parseDate("2013-01-31")));
} catch(ParseException ex){
System.out.println("Unable to parse");
}
}
public static Date parseDate(String dateString) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate;
try {
parsedDate = sdf.parse(dateString);
} catch (ParseException ex) {
try{
parsedDate = sdf2.parse(dateString);
} catch (ParseException ex2){
parsedDate = sdf3.parse(dateString);
}
}
return parsedDate;
}
}
與輸入2013-01-31
我得到的輸出05.07.0036
。
如果我試圖解析31-01-2013
或31.01.2013
我得到31.01.2013
如預期。
我認識到,PROGRAMM會給我一模一樣的輸出,如果我這樣設置模式:
SimpleDateFormat sdf = new SimpleDateFormat("d.M.y");
SimpleDateFormat sdf2 = new SimpleDateFormat("d-M-y");
SimpleDateFormat sdf3 = new SimpleDateFormat("y-M-d");
爲什麼它忽略我的模式字符的數量?
謝謝Teetoo。我沒有在oracle.com類文檔中看到這個。這是一個很好的隱藏陷阱,我們在測試過程中沒有發現。真的是一個糟糕的設計。另一個不好的功能是默認情況下它們是「寬鬆的」,所以你需要setLenient(false)。否則,他們會將各種垃圾解釋爲有效的日期/時間信息。 –