2

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.

2
  • A YearMonth contains no timezone information... Commented Jul 25, 2017 at 7:54
  • Yes I know, and I wonder why the API includes the offset in it and I do not need the offset myself. @assylias Commented Jul 25, 2017 at 8:02

1 Answer 1

4

The correct pattern for the offset +03:00 is XXX (check the javadoc for details - actually in DateTimeFormatterBuilder docs there's a more detailed explanation):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMXXX");
String str = "2014-08+03:00";
YearMonth yearMonth = YearMonth.parse(str, formatter);
System.out.println(yearMonth);

The output will be:

2014-08

Sign up to request clarification or add additional context in comments.

1 Comment

That's the one! Now I see that "Three letters outputs the hour and minute, with a colon, such as '+01:30'." Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.