我有这两种方法现在就写好了。在这种情况下,当我从数据库获取数据字段时,它是BigDecimal格式的。因此,我决定为它编写一个测试( formatDate()方法)。我将BigDecimal传递给该方法,但似乎我写错了这段代码。从我在示例和SimpleDateFormat API中看到的情况来看,我认为我已经正确地编写了代码,但我似乎无法弄清楚抛出parseEx的错误是什么。有人能给我一个提示一下发生了什么吗?
private void loadMap() {
//TODO: Uncomment when finished testing.
//DO OTHER STUFF
BigDecimal bd = new BigDecimal(12051998);
System.out.println(formatDate(bd));
}
private String formatDate(BigDecimal bd) {
String value = bd.toString();
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
return format.parse(value);
} catch (ParseException pEx) {
logger.error(pEx);
return "Bad Date Format";
}
}先谢谢你,温梅斯特,
发布于 2013-04-08 14:37:27
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");应该是
SimpleDateFormat format = new SimpleDateFormat("MMddyyyy");return format.parse(value);// 值应该是日期类型,而不是字符串。
尝试将日期的格式从MMddyyyy更改为MM/dd/yyyy:这对我来说很好。
public static void main(String[] args) throws ParseException {
BigDecimal bd = new BigDecimal(12051998);
String s = bd.toString();
System.out.println(s);
DateFormat originalFormat = new SimpleDateFormat("MMddyyyy");
DateFormat targetFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = originalFormat.parse(s);
String formattedDate = targetFormat.format(date);
System.out.println(formattedDate);
}输出:
12051998
12/05/1998https://stackoverflow.com/questions/15881948
复制相似问题