Change String date format and set into TextView in Android?

32.8k views Asked by At

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());
3

There are 3 answers

0
Ken Wolf On BEST ANSWER

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.

0
AllTooSir On

Change the format string to MM/dd/yyyy, while parse() and use dd MMM yyyy while format().

Sample :

String str ="29/07/2013";
// parse the String "29/07/2013" to a java.util.Date object
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(str);
// format the java.util.Date object to the desired format
String formattedDate = new SimpleDateFormat("dd MMM yyyy").format(date);
0
Deep Adhia On
DateFormat df = new SimpleDateFormat("dd / MM / yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());