Java 7 has introduced support in the SimpleDateFormat
class for ISO 8601 format, via the character X
(instead of lower or upper case Z
Seems that you can use this:
import java.util.Calendar;
import javax.xml.bind.DatatypeConverter;
public class TestISO8601 {
public static void main(String[] args) {
parse("2012-10-01T19:30:00+02:00"); // UTC+2
parse("2012-10-01T19:30:00Z"); // UTC
parse("2012-10-01T19:30:00"); // Local
}
public static Date parse(final String str) {
Calendar c = DatatypeConverter.parseDateTime(str);
System.out.println(str + "\t" + (c.getTime().getTime()/1000));
return c.getTime();
}
}
You can use java.time, the modern Java date and time API, in Java 6. This would seem to me as the nice and also future-proof solution. It has good support for ISO 8601.
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
public class DemoIso8601Offsets {
public static void main(String[] args) {
System.out.println(OffsetDateTime.parse("2012-10-01T19:30:00+0200",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXX")));
System.out.println(OffsetDateTime.parse("2012-10-01T19:30:00+02",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX")));
System.out.println(OffsetDateTime.parse("2012-10-01T19:30:00+02:00"));
System.out.println(OffsetDateTime.parse("2012-10-01T19:30:00Z"));
}
}
Output from this program is:
2012-10-01T19:30+02:00 2012-10-01T19:30+02:00 2012-10-01T19:30+02:00 2012-10-01T19:30Z
It requires that you add the ThreeTen Backport library to your project setup.
org.threeten.bp
with subpackages.As you can see from the code, +02
and +0200
require a formatter where you specify the format of the offset, while +02:00
(and Z
too) conforms with the default format and doesn’t need to be specified.
When reading mixed data, you don’t want to handle each offset format specially. It’s better to use optional parts in the format pattern string:
DateTimeFormatter allInOne
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss[XXX][XX][X]");
System.out.println(OffsetDateTime.parse("2012-10-01T19:30:00+0200", allInOne));
System.out.println(OffsetDateTime.parse("2012-10-01T19:30:00+02", allInOne));
System.out.println(OffsetDateTime.parse("2012-10-01T19:30:00+02:00", allInOne));
System.out.println(OffsetDateTime.parse("2012-10-01T19:30:00Z", allInOne));
Output is the same as above. The square brackets in [XXX][XX][X]
mean that either format +02:00
, +0200
or +02
may be present.
java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).