我在使用SimpleDateFormat(java)将日期时间值转换为预期值时遇到问题,我的预期格式是MM/yyyy
,我想将2个值转换为1格式
输出是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 :(得分: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
失败。