2014-01-21 47 views
0

如何解析總是具有不同格式的日期的字符串(有時是「yyyy-MM-dd HH:mm:ss」或「yyyy-MM-dd'T'HH:mm」或「 yyyy-MM-dd HH:mm「)? 「:毫米YYYY-MM-DD HH」SimpleDateFormat中的Unexacte解析

public static Date test(String value) throws ... { 

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
    return df.parse(value); 


} 

回答

3

我建議你只嘗試解析每個特定的格式 -

如果我使用下面的代碼,如果在值字符串具有其他格式比失敗,抓住ParseException,只是移動到下一格式:

private static final String[] patterns = { 
    "yyyy-MM-dd HH:mm", 
    "yyyy-MM-dd'T'HH:mm", 
    "yyyy-MM-dd HH:mm" 
}; 

public static Date test(String value) throws ... { 
    for (String pattern : patterns) { 
     try { 
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
      return df.parse(value); 
     } catch (ParseException e) { 
      // No-op - move onto the next pattern 
     } 
    } 
    // Do whatever you want here - throw ParseException, or return null 
} 

這很簡單,但濫用例外。您可以使用比較模糊parse(String, ParsePosition)調用來代替:

public static Date test(String value) throws ... { 
    for (String pattern : patterns) { 
     DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
     Date date = df.parse(value, new ParsePosition(0)); 
     if (date != null) { 
      return date; 
     } 
    } 
    // Do whatever you want here - throw ParseException, or return null 
} 

可以有更好的表現 - 你必須對它進行基準測試,以肯定地說。

不幸的是,您必須在每次調用時重新創建SimpleDateFormat對象,但這不是線程安全的問題。另一種選擇是使用Joda Time--這是一個較好的API總體 - 但它不是很清楚你會如何做免例外的方法。 (這很有可能,只是有點模糊了,我懷疑DateTimeFormatter.parseInto會成爲你的朋友。)

+0

如果新的未知模式會來? – Igor

+1

@Igor:它從哪裏來? (如果你想回答某些問題,順便提一下,它應該在你的問題中。)你需要有你期望的模式列表*在某處*。如果你真的想讓它變得非常動態,你可以從文件或數據庫加載它們。 –

+0

這是源代碼的一部分,我們的服務器應用程序和日期不同的格式的字符串來自客戶端(客戶端應用程序在IPhone/iPad上)我們一直只有「yyyy-MM-dd HH:mm:ss」作爲傳入模式,但昨天我在日誌中也看到了這個模式「yyyy-MM-dd HH:mm」和錯誤「Unparseable date ...」我不知道什麼樣的模式會來我們。我們的IOS開發人員將在下一個版本中修改日期的創建(他將使其獨立於Iphone設置),但現在我應該立即在服務器端進行更正。當然,我必須在我的問題中寫下它。對不起 – Igor