1

I have a literal string which is " 2015-12-08T13:04:51Z " , which I would like to convert to date format to show : December 08, 2015 3:04:51 pm. But every time I try all the solutions available online my app crashes with a bad date format exception . How do I get it to display the requiredformat. The current code I am using is :

            String mydate = ((Search) searchResult).getmydate();

which returns "2015-12-08T13:04:51Z " I tried this:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
    try {  
        Date date = format.parse(mydate);  
    } catch (ParseException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }
 result = date;

But every single time I do that it crashes. Any ides how to go about it in the UTC time zone in the required format?

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • "But every single time I do that it crashes" -- use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare Dec 16 '15 at 21:26
  • even so I am not able to figure out how to convert the given string to the required date time format? how do I go about it? –  Dec 16 '15 at 21:27
  • Well, for starters, you edit your question and post the stack trace. How are we supposed to help you with your crash if we do not know what the crash *is*? – CommonsWare Dec 16 '15 at 21:29
  • sure.also, is there a generic way to convert a literal string like " 2015-12-08T13:04:51Z " to something like " December 08, 2015 3:04:51 pm" –  Dec 16 '15 at 21:31
  • Parse the original string into a `Date`, then format the `Date` into the desired string. Whether you use `SimpleDateFormat` or a library is up to you. – CommonsWare Dec 16 '15 at 21:38
  • what is the simpledateformat for something to look like "december 6, 2015 10:55am –  Dec 16 '15 at 21:51

1 Answers1

1

try this method

public static String readDate(String dateStr) throws ParseException {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date d = format.parse(dateStr);

    format = new SimpleDateFormat("MMMM dd, yyyy hh:mm:ss a");

    return format.format(d);
}

if it has an error try to trim your mydate variable.

Vasileios Pallas
  • 4,801
  • 4
  • 33
  • 50