84. Calculating the middle of the month
Let’s imagine that we have a LocalDate
and we want to calculate from it another LocalDate
representing the middle of the month. This can be achieved in seconds if we know that the LocalDate
API has a method named lengthOfMonth()
, which returns an integer representing the length of the month in days. So, all we have to do is calculate lengthOfMonth()
/2 as in the following code:
public static LocalDate middleOfTheMonth(LocalDate date) {
return LocalDate.of(date.getYear(), date.getMonth(),
date.lengthOfMonth() / 2);
}
In the bundled code, you can see a solution based on the Calendar
API.