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?
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.
You can just use: Date yourDate = new Date(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); String date = DATE_FORMAT. format(yourDate);
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
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.
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");
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); } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With