2012-11-12 41 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 –