I'm having problems with parsing a special string representing an year and a month with an offset like this: 2014-08+03:00
.
The desired output is an YearMonth
.
I have tested creating a custom DateTimeFormatter
with all kind of patterns, but it fails and a DateTimeParseException
is thrown.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMZ");
TemporalAccessor temporalAccessor = YearMonth.parse(month, formatter);
YearMonth yearMonth = YearMonth.from(temporalAccessor);
What is the correct pattern for this particular format?
Is it even possible to create a DateTimeFormatter
that parses this String
, or should I manipulate the String "2014-08+03:00"
and remove the offset manually to "2014-08"
, and then parse it into a YearMonth
(or to some other java.time
class)?
Edit:
I further investigated the API and its .xsd schema-file where the attribute is listed as <xs:attribute name="month" type="xs:gYearMonth"/>
where the namespace is xmlns:xs="http://www.w3.org/2001/XMLSchema">
So apparently the type of the attribute is DataTypeConstans.GYEARMONTH where "2014-08+03:00" is a valid format.
This answer explains how to convert a String
to a XMLGregorianCalendar
, from where it is possible to convert to an YearMonth
via an OffsetDateTime
.
XMLGregorianCalendar result = DatatypeFactory.newInstance().newXMLGregorianCalendar("2014-08+03:00");
YearMonth yearMonth = YearMonth.from(result.toGregorianCalendar().toZonedDateTime().toOffsetDateTime());
However I am still curious if it possible to parse the string "2014-08+03:00"
directly to an YearMonth
only using a custom java.time.DateTimeFormatter
.