2012-11-12 22 views
2

我有將日期時間值的問題預計一個與SimpleDateFormat的(JAVA),我預計格式爲MM/yyyy,我想2個值轉換爲僅1格式轉換日期時間值有望與SimpleDateFormat的

  1. MM-YYYY例如05-2012
  2. YYYY-MM例如2012-05

輸出中是05/2012。

我實現的東西看起來像下面

String expiry = "2012-01"; 
try { 
    result = convertDateFormat(expiry, "MM-yyyy", expectedFormat); 
} catch (ParseException e) { 
    try { 
     result = convertDateFormat(expiry, "yyyy-MM", expectedFormat); 
    } catch (ParseException e1) { 
     e1.printStackTrace(); 
    } 
    e.printStackTrace(); 
} 

private String convertDateFormat(String date, String oPattern, String ePattern) throws ParseException { 
    SimpleDateFormat normalFormat = new SimpleDateFormat(oPattern); 
    Date d = normalFormat.parse(date); 
    SimpleDateFormat cardFormat = new SimpleDateFormat(ePattern); 
    return cardFormat.format(d); 
} 

現在,返回值是6808,我不知道爲什麼。

請幫助我解決這個問題。

+0

如果您解析2012-05,它真的嘗試第二種方式:

這在這裏詳細解釋?還是從第一種格式解析並得到錯誤的結果?在選擇格式化方法之前,您可以在「 - 」位置創建條件。 –

+2

請接受答案,直到現在你都沒有接受任何答案。 –

+0

我同意@Quoi你根本不接受任何答案。 – user75ponic

回答

2

添加SimpleDateFormat#setLenient()convertDateFormat方法:

private String convertDateFormat(String date, String oPattern, String ePattern) throws ParseException { 
    SimpleDateFormat normalFormat = new SimpleDateFormat(oPattern); 
    normalFormat.setLenient(false); /* <-- Add this line -- */ 
    Date d = normalFormat.parse(date); 
    SimpleDateFormat cardFormat = new SimpleDateFormat(ePattern); 
    return cardFormat.format(d); 
} 

這將使convertDateFormat失敗,如果日期不正確。 http://eyalsch.wordpress.com/2009/05/29/sdf/

+0

非常好,謝謝@maba –