Possible Duplicate:
Converting ISO8601-compliant String to java.util.Date
I'm trying to convert this String:
2011-06-07T14:08:59.697-07:00
To a Java Date, so far, here's what I did:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S");
Date date1 = sdf.parse("2011-06-07T14:08:59.697", new java.text.ParsePosition(0));
Almost everything is good, except the most important part, the timezone !!
The problem with SimpleDateFormat is that it expect a TimeZone in +/-hhmm
and mine is in +/-hh:mm
format.
Also, and I don't know why, this works:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S Z");
Date date1 = sdf.parse("2011-06-07T14:08:59.697 -0700", new java.text.ParsePosition(0));
But this does not (the space before the timezone):
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ");
Date date1 = sdf.parse("2011-06-07T14:08:59.697-0700", new java.text.ParsePosition(0));
What is the correct format to transform this date 2011-06-07T14:08:59.697-07:00
to a java date ?
Thanks for your help!
Java SimpleDateFormat doesn't support colon in the timezone information. You should use other implementation such as JodaTime.
Example usage:
maven pom.xml dependency if needed:
Hope it helps.
The problem with
S
is that it will produce three digit milli-seconds but will not parse three digits.prints
It appears you need to remove the
:
in the timezone.That looks like the ISO 8601 standard date and time format as it is used in XML. Unfortunately, Java's
SimpleDateFormat
doesn't support that format properly, because it can't deal with the colon in the timezone.However, the
javax.xml
package contains classes that can deal with this format.If you need it as a
java.util.Calendar
then you can calltoGregorianCalendar()
on it:And ofcourse you can get a
java.util.Date
out of that:You could also use the popular Joda Time library which natively supports this format (and has a much better API for dealing with dates and times than Java's standard library).
It looks like DateFormat can't find the end of milliseconds and the start of timezone. Regex to the rescue!
This is a work around:
The regex puts a space in and this code executes without error.