Reputation: 577
I have these two methods that are written right now. As the scenario goes, when I grab a data field from the database, it is in BigDecimal format. So I decided to write a test for it (the formatDate() method). I pass in the BigDecimal to the method, but it appears I have written some peice of this code wrong. From what I have seen in examples and the SimpleDateFormat API, I think I have written the code correctly, but I cannot seem to figure out what is going wrong to have it throw a parseEx. Can someone give me a hint at what is going on?
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";
}
}
Thanks in advance, Warmest Regards,
Upvotes: 0
Views: 1848
Reputation: 12843
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
should be
SimpleDateFormat format = new SimpleDateFormat("MMddyyyy");
return format.parse(value);
// value should be of Date type not String .
Try this to change format of the date from MMddyyyy to MM/dd/yyyy: It works fine for me.
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);
}
Output:
12051998
12/05/1998
Upvotes: 5