Search code examples
javaandroiddatesimpledateformatandroid-datepicker

parse a date from string gives exception in android


I want to parse a string from string to date ,Date is of format like Tuesday March 19,2015. I want to parse and format it as yyyy-dd-mm format. The below code gives me exception that "unparceble date".

Code :

DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
try {
    date1 = df1.parse(currentDate);
    System.out
            .println("============my formated date====================" + date1.toString());
    Calendar cal = Calendar.getInstance();
    cal.setTime(date1);
    cal.add(Calendar.DATE, 10); // add 10 days

    date1 = cal.getTime();

    System.out.println("==============added date==============" + date1.toString());

Solution

  • I have created one common function for convert date format. You have to pass old Date format, new date format and date.

    public static String convertDateFormat(String oldFormat, String newFormat, String inputDate)
        {
            DateFormat theDateFormat = new SimpleDateFormat(oldFormat);
            Date date = null;
    
            try
            {
                date = theDateFormat.parse(inputDate);
            }
            catch (ParseException parseException)
            {
                // Date is invalid. Do what you want.
            }
            catch (Exception exception)
            {
                // Generic catch. Do what you want.
            }
    
            theDateFormat = new SimpleDateFormat(newFormat);
            return theDateFormat.format(date).toString();
        }
    

    // Call funcation

    String convertedDate = convertDateFormat("EEEE MMM dd,yyyy","yyyy-MM-dd",dateToConvert);