This may solve it for you or at least be a start:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendPattern("XX")
.toFormatter();
String[] stringsPassed = {
"2018-11-01T16:26:15+0100",
"2018-10-31T08:27:00.0000000Z"
};
for (String sample : stringsPassed) {
OffsetDateTime odt = OffsetDateTime.parse(sample, formatter);
System.out.println(odt);
}
Output:
2018-11-01T16:26:15+01:00
2018-10-31T08:27Z
It doesn’t parse all thinkable ISO 8601 strings, but may parse those you can get. Since you have only shown us two samples, I cannot know.
java.time, the modern Java date and time API, is quite ISO 8601 friendly. It handles presence and absence of seconds and fraction of second (up to 9 decimals). This is what I am using DateTimeFormatter.ISO_LOCAL_DATE_TIME
for in the code. The slight issue is that the built-in DateTimeFormatter.ISO_OFFSET_DATE_TIME
, which would otherwise seem right here, requires a colon in the UTC offset, as in +01:00
. Instead I am using format pattern XX
. It accepts an offset without colon and also accepts Z
as in your second example. If still more flexibility required, you may look into optional parts in the formatter. Check the documentation.
Joda-Time? Not recommended when you are using Java 8. A couple of quotes from the Joda-Time home page:
Joda-Time is the de facto standard date and time library for Java
prior to Java SE 8. Users are now asked to migrate to java.time
(JSR-310).
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time
(JSR-310).
Even on Java 6 and 7 I would have recommended the backport of java.time over Joda-Time.
Links