kosmičák
kosmičák

Reputation: 1043

parsing dates with month without leading 0

I'd like to parse dates consisting of month (1-12) and year like eg:

1.2015
12.2015

into LocalDate

I get an exception using 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 obtain LocalDate from TemporalAccessor: {MonthOfYear=6, Year=2015},ISO of type java.time.format.Parsed

The documentation ist not clear for me on the short month format.

edit: I guess the problem is the missing day of month?

Upvotes: 3

Views: 3189

Answers (5)

long
long

Reputation: 59

LocalDate represents an actual date , so you can not use just a year and a month to get LocatDate

you can use

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

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

Upvotes: 2

assylias
assylias

Reputation: 328639

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 need the first and last day of the month:

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

Upvotes: 8

Rene M.
Rene M.

Reputation: 2690

I can't find exactly definition of the behavior in the docs. But my guess is that you need a Day to fullfill the temporal object LocalDate.

Try this:

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

Upvotes: 1

kosmičák
kosmičák

Reputation: 1043

It seems the problem is really the missing day of month. My workaround is to set it:

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

Upvotes: 3

nafas
nafas

Reputation: 5423

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

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);
}

Upvotes: -2

Related Questions