-1

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());
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
John Watson
  • 15
  • 2
  • 8

2 Answers2

1

You must parse it into the date of your current format before format it to another date

DateFormat df_parse = new SimpleDateFormat("EEEE MMM dd,yyyy");
Date date_parse = df_parse.format(currentDate);
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
date1 = df1.parse(date_parse);
Randyka Yudhistira
  • 3,612
  • 1
  • 26
  • 41
0

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);
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • can you please help me in one more thing?what should i do if i want to add numbers to date.means i want to add 10 or 15 days to my date. – John Watson Mar 17 '15 at 06:25
  • You can find answer from this link - http://stackoverflow.com/questions/8738369/how-to-add-days-into-the-date-in-android' – Chirag Mar 17 '15 at 06:38