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.

andersnylund
  • 190
  • 2
  • 10

1 Answers1

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

  • 2
    That's the one! Now I see that "Three letters outputs the hour and minute, with a colon, such as '+01:30'." Thanks! – andersnylund Jul 25 '17 at 12:06