Simpledateformat unparseable date

Carl Bruiners picture Carl Bruiners · Mar 9, 2018 · Viewed 27.4k times · Source

I have a String in a database (match.getDate) that has the following date format:

01/04/2018

This is the date I want to format, stored as day/month/year. I want to format this for my Android app.

I want to format the date into:

Sun 01 Apr 2018

My code below:

SimpleDateFormat fDate = new SimpleDateFormat("dd/MM/yyyy");
try {
    textViewDate.setText(fDate.parse(match.getDate()).toString());
} catch (ParseException ex) {
    System.out.println(ex.toString());
}

This outputs:

Sun Apr 08 00:00:00 GMT+00:00 2018.

I have also tried "EE, MM d, yyyy", but it gives me:

java.text.ParseException: Unparseable date: "01/04/2018"

Answer

Harsh Patel picture Harsh Patel · Mar 9, 2018

Use this date formatter method I have created

    public static String dateFormater(String dateFromJSON, String expectedFormat, String oldFormat) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(oldFormat);
    Date date = null;
    String convertedDate = null;
    try {
        date = dateFormat.parse(dateFromJSON);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(expectedFormat);
        convertedDate = simpleDateFormat.format(date);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return convertedDate;
}

and call this method like

dateFormater(" 01/04/2018" , "EE dd MMM yyyy" , "dd/MM/yyyy") 

and you will get the desired output