Reactormonk
Reactormonk

Reputation: 21700

Parsing into YearMonth

I would like to parse two separate strings "1982" and "SEP" into a java.time.YearMonth object.

java.time.YearMonth.parse("1978 SEP", java.time.format.DateTimeFormatter.ofPattern("yyyy LLL"))

gives me

java.time.format.DateTimeParseException: Text '1978 SEP' could not be parsed at index 5
  at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
  at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
  at java.time.YearMonth.parse(YearMonth.java:295)

Upvotes: 2

Views: 4519

Answers (2)

Roberto Zanichelli
Roberto Zanichelli

Reputation: 66

I tried your code, if you take a look on how java print the date it uses Upper case in the first letter of the month (in my execution) Just type Sep instead of sep, and use MMM instead of LLL in the string pattern.

Before using a string pattern to parse dates see how they are printed on the system output then write your string pattern accordingly.

this example works only on locale english, in locale italian the string date pattern are differnt so if you change locale i suggest you to modify the parsers

try {

            java.time.YearMonth.parse("1978 Sep", java.time.format.DateTimeFormatter.ofPattern("yyyy MMM" ));

        }

        catch(DateTimeParseException e)

        {

            e.printStackTrace();

        }

}

Upvotes: 0

Tunaki
Tunaki

Reputation: 137104

There are 3 (possibly 2) problems here:

  • Your locale isn't English, so "SEP" can't be understood as September. This can be fixed by setting the English locale to the formatter.
  • DateTimeFormatter is case sensitive by default so you need to build a case insensitive formatter.
  • You shouldn't use the "L" token but "M" instead: refer to this question.

The following will work:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                    .parseCaseInsensitive()
                                    .appendPattern("yyyy MMM")
                                    .toFormatter(Locale.ENGLISH);
System.out.println(YearMonth.parse("1978 SEP", formatter));

Upvotes: 9

Related Questions