-1

I am getting Time from an api in this format
"2018-03-07T11:19:54.686Z" ..... How to convert this String data to mm-dd-yyyy date format in android.

SimpleDateFormat format = new SimpleDateFormat(" MM,dd,yy");    
String date = format.format(Date.parse(data));

I have tried using the above two but there is a parse error.

  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. Use for example `OffsetDateTime.parse("2018-03-07T11:19:54.686Z").format(DateTimeFormatter.ofPattern("MM-dd-uuuu"))`. – Ole V.V. Mar 08 '18 at 07:56
  • Possible duplicate of [Changing String date format](https://stackoverflow.com/questions/34846358/changing-string-date-format) – Ole V.V. Mar 08 '18 at 07:58
  • This question has been asked and answered with variations very many times already. I can’t believe you didn’t find it in your search. :-) – Ole V.V. Mar 08 '18 at 07:58

2 Answers2

4

First you have to parse the given date "2018-03-07T11:19:54.686Z" in the same format and then you can apply formatting with the desired format.

SimpleDateFormat parseDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");    
String date = format.format(parseDateFormat.parse(data));
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
  • There is a null pointer exception code java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference – Samuel Mamootil Mar 08 '18 at 07:26
0

you used below code and show your format according to date.

        String date="2018-03-07T11:19:54.686Z";
    SimpleDateFormat parseDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    DateFormat formatdate = new SimpleDateFormat("MM,dd,yy");//if show mm-dd-yy

    try {
        Date date1=parseDateFormat.parse(date);
        Log.d("New Date",formatdate.format(date1));
    } catch (ParseException e) {
        e.printStackTrace();
    }
  • there is an error while using above code java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference – Samuel Mamootil Mar 08 '18 at 07:21
  • i am used above code in oncreate method it give mm,dd,yy format in new date it working.check your api date comeing same format define above. –  Mar 08 '18 at 07:24