0

I am trying to parse date JSON response in java

"2014-12-16T13:17:27.943Z"

This is the format of date which I am getting in the JSON.

What is the string pattern to be used for SimpleDateFormatto convert it to Date object.

Chaitanya
  • 3,399
  • 6
  • 29
  • 47

1 Answers1

2

You can try to use

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")

This format will take care of both the formats like

"2014-12-16T13:17:27.943Z" and "2014-12-16T13:17:27.943+0000"

You can also check JodaTime if you are open to use some other Java's built-in Date/Time/Calendar classes.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • What does that last four characters correspond to ? – Chaitanya Apr 19 '15 at 05:56
  • @Chaitanya:- The X pattern is new for Java 7. See this: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – Rahul Tripathi Apr 19 '15 at 05:59
  • Ok fine .. actually i was seeing a different link https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html So I got confused. Thanks. – Chaitanya Apr 19 '15 at 06:01
  • I am using Java compiler 1.7 in eclipse. But still it says not able to recognize the character X. Its throwing an error in this case. – Chaitanya Apr 19 '15 at 06:09
  • @Chaitanya:- Can you tell whats the error? – Rahul Tripathi Apr 19 '15 at 06:10
  • 04-19 02:12:25.312: E/AndroidRuntime(1610): Caused by: java.lang.IllegalArgumentException: Unknown pattern character 'X' 04-19 02:12:25.312: E/AndroidRuntime(1610): at java.text.SimpleDateFormat.validatePatternCharacter(SimpleDateFormat.java:314) 04-19 02:12:25.312: E/AndroidRuntime(1610): at java.text.SimpleDateFormat.validatePattern(SimpleDateFormat.java:303) – Chaitanya Apr 19 '15 at 06:12
  • @Chaitanya:- I am not sure but most probably you need to replace all colons `:` from you time. Try this regex and check `yourDate= yourDate.replaceAll(":(\\d\\d)$", "$1")` – Rahul Tripathi Apr 19 '15 at 06:13
  • @Chaitanya:- Also try to use this: `DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");` – Rahul Tripathi Apr 19 '15 at 06:15
  • Ok sure. I will try that out and let u know. – Chaitanya Apr 19 '15 at 06:15
  • @Chaitanya:- Your error suggests that you are using the Android so you need the Z format and also refer android doc: http://developer.android.com/reference/java/text/SimpleDateFormat.html – Rahul Tripathi Apr 19 '15 at 06:22