Im trying parse a date from a JSONObject
"timcre_not":"2013-12-11 21:25:04.800842+01"
and I parse with
mDate = new SimpleDateFormat("y-M-d h:m:s.SSSSSSZZ",
Locale.ENGLISH).parse(json.getString("timcre_not"));
but the mDate value is:
Wed Dec 11 21:38:24 CET 2013
What is happening?
This should be the solution: Date object SimpleDateFormat not parsing timestamp string correctly in Java (Android) environment
SimpleDateFormat cannot take microseconds, only milliseconds.
The answer by treeno is correct.
Joda-Time
As an alternative, you can use the third-party open-source Joda-Time. Joda-Time is often used to supplant the java.util.Date & Calendar classes found in Java (and Android).
ISO 8601
The string you have is loosely in ISO 8601 format. Replace that SPACE with a LATIN CAPITAL LETTER T "T" character to get a strict ISO 8601 format.
Joda-Time's
DateTime
class accepts an ISO 8601 string directly to its constructor. One catch: As with java.util.Date, a DateTime tracks only to the millisecond not microsecond. But in Joda-Time, rather than throw an error, the DateTime merely truncates (ignores) the extra (beyond 3) decimal places.Example Code
Here is some example code using Joda-Time 2.3 and Java 8.
Dump to console…
When run…
Java 8
I tried using the new java.time.* classes in Java 8 to parse your string.
Unfortunately, the parser did not tolerate the time zone offset being the shortened
+01
. I tried the longer+01:00
and it worked. This seems to be a flaw in the Java implementation, not your string. The shortened offset is allowed in ISO 8601. While both I and RFC 3339 (a near-profile of ISO 8601) prefer using the longer+01:00
, the ISO standard doe allow it and so should the java.time.* classes. I filed Bug Id: 9009717 with Oracle.Get Better Data
If possible, suggest to the source of your date that they use the more strict and common ISO 8601 format including: