0

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,

  • Josh
ResourceReaper
  • 555
  • 2
  • 10
  • 27

1 Answers1

5
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
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
  • I have updated the method to MMddyyyy The message I am getting is: Unparseable date: "12051998" – ResourceReaper Apr 08 '13 at 14:43
  • @JoshGooding you want to change format of the date from MMddyyyy to MM/dd/yyyy ? – Achintya Jha Apr 08 '13 at 14:47
  • yes I want to convert 12051998 to 12/05/1998. It worked. I was unaware that I had to basically do a double conversion on the date. I tried doing it in one step, and didn't realize. Seems like you cannot do everything in one step. Thank you! – ResourceReaper Apr 08 '13 at 15:31