Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SimpleDateFormat pattern for W3C XML dates with timezone [duplicate]

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?

like image 501
PNS Avatar asked May 16 '12 08:05

PNS


People also ask

What timezone does SimpleDateFormat use?

Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy , derived from this milliseconds value.

How do you change date format to MM DD YYYY in Java?

You can just use: Date yourDate = new Date(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); String date = DATE_FORMAT. format(yourDate);

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

What is the difference between DateFormat and SimpleDateFormat?

The java SimpleDateFormat allows construction of arbitrary non-localized formats. The java DateFormat allows construction of three localized formats each for dates and times, via its factory methods.


2 Answers

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"); 
like image 65
assylias Avatar answered Sep 18 '22 16:09

assylias


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);     } }; 
like image 24
Vlad Avatar answered Sep 18 '22 16:09

Vlad