PNS PNS - 2 months ago 12
Java Question

Java SimpleDateFormat pattern for W3C XML dates with timezone

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

How about something like:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"){ 
    public Date parse(String source,ParsePosition pos) {    
        return super.parse(source.replaceFirst(":(?=[0-9]{2}$)",""),pos);
    }
};
Comments