使用SimpleDateFormat将日期时间值转换为预期值

时间:2012-11-12 10:26:44

标签: java simpledateformat dataformat

我在使用SimpleDateFormat(java)将日期时间值转换为预期值时遇到问题,我的预期格式是MM/yyyy,我想将2个值转换为1格式

  1. MM-yyyy,例如05-2012
  2. yyyy-MM,例如2012-05
  3. 输出是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,我不知道原因。

    请有人帮我解决此案。

1 个答案:

答案 0 :(得分: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/