Java SimpleDateFormat pattern for W3C XML dates with timezone

PNS picture PNS · May 16, 2012 · Viewed 45.6k times · Source

I am trying to parse a W3C XML Schema date like the following

"2012-05-15T07:08:09+03:00"

which complies with the ISO 8601 version of the W3C XML Schema dateTime specification.

In the above date, the timezone identifier is "+03:00", but no SimpleDateFormat pattern apparently exists to represent it.

If the timezone were "+0300", then Z (uppercase) would be applicable and the SimpleDateFormat pattern would be

yyyy-MM-dd'T'HH:mm:ssZ

Similarly, if the timezone were "GMT+03:00", then z (lowercase) would be applicable and the SimpleDateFormat pattern would be

yyyy-MM-dd'T'HH:mm:ssz

(uppercase 'Z' also works, by the way).

So, is there a SimpleDateFormat pattern or workaround to represent the above date without preprocessing of the date string?

Answer

assylias picture assylias · May 16, 2012

If you use Java 7+, this pattern should work (X is for the ISO 8601 time zone):

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");