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?
source to share
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();
source to share
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);
source to share
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);
}
source to share