As I just learned, there are now special methods for it.
You can do it like this now:
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");
public static final DateTimeFormatter OUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static LocalDate[] getFirstAndLastDateOfMonthNew(String yearAndMonth) {
final LocalDate[] result = new LocalDate[2];
final YearMonth yearMonth = YearMonth.parse(yearAndMonth, FORMATTER);
result[0] = yearMonth.atDay(1);
result[1] = yearMonth.atEndOfMonth();;
return result;
}
The old way would have been:
Just add the 01
to the date and parse it. The add a month and subtract a day.
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
public static final DateTimeFormatter OUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static LocalDate[] getFirstAndLastDateOfMonth(String yearAndMonth) {
final LocalDate[] result = new LocalDate[2];
final LocalDate first = LocalDate.parse(yearAndMonth + "01", FORMATTER);
final LocalDate last = first.plusMonths(1).minusDays(1);
result[0] = first;
result[1] = last;
return result;
}