我在使用 SimpleDateFormat (java) 将日期时间值转换为预期值时遇到问题,我的预期格式为 MM/yyyy
,并且我只想将 2 个值转换为 1 种格式
- 例如 MM-yyyy 05-2012
- 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
,我不知道为什么。
请任何人帮助我解决这个案子。
最佳答案
添加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
失败。
关于java - 使用 SimpleDateFormat 将日期时间值转换为预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13342025/