Change String date format and set into TextView in Android?

Developer picture Developer · Jul 29, 2013 · Viewed 30.1k times · Source

I want to change my date format that is in as

String date ="29/07/13";

But it is showing me the error of *Unparseable date: "29/07/2013" (at offset 2)* I want to get date in this format 29 Jul 2013.

Here is my code that i am using to change the format.

tripDate = (TextView) findViewById(R.id.tripDate);
    SimpleDateFormat df = new SimpleDateFormat("MMM d, yyyy");
            try {
                oneWayTripDate = df.parse(date);
            } catch (ParseException e) {

                e.printStackTrace();
            }
            tripDate.setText(oneWayTripDate.toString());

Answer

Ken Wolf picture Ken Wolf · Jul 29, 2013

Try like this:

String date ="29/07/13";
SimpleDateFormat input = new SimpleDateFormat("dd/MM/yy");
SimpleDateFormat output = new SimpleDateFormat("dd MMM yyyy");
try {
    oneWayTripDate = input.parse(date);                 // parse input 
    tripDate.setText(output.format(oneWayTripDate));    // format output
} catch (ParseException e) {
    e.printStackTrace();
}

It's a 2-step process: you first need to parse the existing String into a Date object. Then you need to format the Date object into a new String.