Parsing with month without specifying 0

I would like to parse dates consisting of month (1-12) and year, for example, for example:

1.2015
12.2015

      

in LocalDate

I am getting an exception with this code:

final DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("M.yyyy");
LocalDate monthYearDate = LocalDate.parse(topPerformanceDate, monthYearFormatter);

      

java.time.format.DateTimeParseException: text "6.2015" could not be parsed: unable to get LocalDate from TemporalAccessor: {MonthOfYear = 6, Year = 2015}, ISO type java.time.format.Parsed

The documentation is unclear to me in a short month format.

edit: I guess the problem is that there is no month to month?

+3


source to share


5 answers


Since your input is not a date, but rather a month / year combination, I would suggest using the YearMonth

class:

String input = "1.2015";
YearMonth ym = YearMonth.parse(input, DateTimeFormatter.ofPattern("M.yyyy"));

      



In the comments, you add that you want the first and last day of the month:

LocalDate firstOfMonth = ym.atDay(1);
LocalDate endOfMonth = ym.atEndOfMonth();

      

+8


source


The problem seems to be that this is indeed the missing day of the month. My workaround is to install it:



    final DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("d.M.yyyy");
    month = LocalDate.parse("1." + topPerformanceDate, monthYearFormatter);

      

+3


source


LocalDate represents the actual date, so you can't just use the year and month to get the LocatDate

you can use

 YearMonth yearMonth =YearMonth.from(monthYearFormatter.parse("6.2015"));

      

and you can format month str to 0x before formatting it and use MM.yyyy pattern to format

+2


source


I cannot find the exact definition of the behavior in the docs. But I assume you need a Day to populate the temporary LocalDate object.

Try the following:

final DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("d.M.yyyy");
LocalDate monthYearDate = LocalDate.parse("1." + topPerformanceDate, monthYearFormatter);

      

+1


source


there are only two cases, why don't you just try both of them?

final DateTimeFormatter monthYearFormatter1 = DateTimeFormatter.ofPattern("MM.yyyy");
final DateTimeFormatter monthYearFormatter2 = DateTimeFormatter.ofPattern("M.yyyy");

LocalDate monthYearDate;
try{
    monthYearDate= LocalDate.parse(topPerformanceDate, monthYearFormatter1);
}catch(DateTimeParseException e ){
    monthYearDate=LocalDate.parse(topPerformanceDate, monthYearFormatter2);
}

      

-2


source







All Articles