Unparseable date. Parse Exception comparing two dates

389 views Asked by At

I am trying to produce a list based on a date. I keep getting a Parse exception. I thought I had the dates in the exact same format. Maybe I missed something. I have played with this for hours with no success. Any help would be appreciated.

public static List<String> getMonthlyDates(Date startdate, Date enddate) {
    List<String> dates = new ArrayList<String>();
    Calendar calendar = new GregorianCalendar();


    calendar.setTime(startdate);

    while (calendar.getTime().before(enddate)) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String result = df.format(calendar.getTime());
        dates.add(result);
        calendar.add(Calendar.MONTH, 1);
    }
    return dates;
}

Calendar Mcalendar = Calendar.getInstance();
String dd = editbillduedate.getText().toString();
     //Which shows correctly in the format of 2015-Jun-15 
SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd"); 
     //it makes no difference if format is yyyy-mm-dd
Date date;
        try {
 //THIS LINE BELOW IS WHERE I AM GETTING THE ERROR
            date = format.parse(dd);
            Mcalendar.add(Calendar.DAY_OF_YEAR, 365);
            final Date newDate2 = Mcalendar.getTime();

            List<String> dateList = getMonthlyDates(date, newDate2);

            for (final String d1 : dateList) {
            //Does something irrelevant

            }
            } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
1

There are 1 answers

2
Gabriella Angelova On BEST ANSWER

If you want to parse dates in the same format like 2015-Jun-15, you should change your SimpleDateFormat to have THREE characters for the month element like this: yyyy-MMM-dd. So change this :

SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd"); 

to:

SimpleDateFormat  format = new SimpleDateFormat("yyyy-MMM-dd"); 

and this:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

to:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MMM-dd");