SimpleDateFormat parsing returns null
android, date, java, json
Solution
The `null` value is being returned from exception block due the first `SimpleDateFormat` returning `null` as a result of an invalid date format.
The `Z`pattern is used to denote timezone patterns. To accept a literal `Z` character, you need to surround the character with single quotes.
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS'Z'", Locale.US);
Also, you can do the same with the `T` character if you don't wish to do a manual replace:
Instead of
String tim = time.replace("T", " "); // remove
just use `time` and use:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
Problem
I have a date value of the type "2013-03-28T15:16:58.000Z". I want to convert it to "dd-MMM-yyyy" format. For that, I have used the following code: ``` public static String getTime(String time) { try { String tim = time.replace("T", " "); SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", Locale.US); SimpleDateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy", Locale.US); return df2.format(df1.parse(tim)); } catch (ParseException e) { return null; } } ``` I got this solution from a variety of posts here in StackOverflow. But this code still returns null. Can anyone tell me why?