-1

I am currently parsing date from PHP server api and the date from api is "1970-04-22" now I need to display this date as "04-22-1970". I tried following code but its not display the exact format.

String date = jsonObject.optString("date"); // output is "1970-04-22"
SimpleDateFormat spf=new SimpleDateFormat("MMM, dd,yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("MMM dd yyyy");
date = spf.format(newDate);
Log.e("date", String.valueOf(date));
Gunners.Ranju
  • 101
  • 3
  • 15
  • what does it display to you ? show us the log – Chief Madog Feb 23 '17 at 11:45
  • @Selvin Oops!! I posted wrong one. I've edited the actual code. Can you check it out! Thanks!! – Gunners.Ranju Feb 23 '17 at 11:49
  • it doesnt matter ... it is still wrong format ... MMM is month as 3 letters shorcut ... your "1970-04-22" doesn't contains it, it also doesn't contains "," nor hours minutes nor seconds ... **again, you have tu ask youself what is a format of "1970-04-22"** it's year as 4 digit, dash, month as 2 digits, dash, days as 2 digits – Selvin Feb 23 '17 at 11:50
  • 1
    Possible duplicate of [How to parse a date?](http://stackoverflow.com/questions/999172/how-to-parse-a-date) – Selvin Feb 23 '17 at 11:57

1 Answers1

0
String tempDate = "1970-04-22";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Date date1=null;
        try {
            date1 = simpleDateFormat.parse(tempDate);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat newformat = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
        String dateInReqFormat = newformat.format(date1);

In these cases you have to first convert the existing format to a date and then format the date to the string as you want it .

Arpan Sharma
  • 2,142
  • 11
  • 22