-3

I am trying to convert a date of MMM, dd yyyy to a format of dd/mm/yyyy in order to update a date picker but I get an error in parse method on the following:

SimpleDateFormat format = new SimpleDateFormat("MMM, dd yyyy");
Date newDate = format.**parse**(strCurrentDate);

format = new SimpleDateFormat("dd/MM/yyyy");
String date = format.format(newDate);

and

 String str[] = date.split("/");
 int myday = Integer.parseInt(str[0]);
 int mymonth = Integer.parseInt(str[1]);
 int myyear = Integer.parseInt(str[2]);
 dp.updateDate(myday,mymonth,myyear);

What I am doing wrong here? Should I enclose it with try / catch? thank you

2 Answers2

2

This will sure work.

 String inputPattern = "MMM, dd yyyy";
        String outputPattern = "dd/MM/yyyy";
        SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern, Locale.ENGLISH);
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern,Locale.ENGLISH);

        Date date = null;
        String str = null;

        try {
            String strCurrentDate = "Sep, 1 2016";
            date = inputFormat.parse(strCurrentDate);// it's format should be same as inputPattern
            str = outputFormat.format(date);
            Log.e("Log ","str "+str);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
ViramP
  • 1,659
  • 11
  • 11
0

You need to first parse your string using a SimpleDateFormatter(SDF) like follows

String strDate = "MM, dd yyyy";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date dateStr = formatter.parse(strDate);

Use this to parse the string into a Date, and then your other SDF to turn that Date into the format you want.

Gaurav Sarma
  • 2,248
  • 2
  • 24
  • 45