2

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

  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,我不知道为什么。

请任何人帮助我处理这个案子。

4

1 回答 1

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/

于 2012-11-12T10:58:20.060 回答