user666 :
I am using Java 8, i need to count how many days we have in an interval having index = x. Example: from 1-1-2019 till 31-1-2019 we have 1 occurrence of Day 1.
I do not want the range of days, just the count of day X If its the last day of month, i want to count them all example: 30 +30 +31+28
user666 :
public long getNumberOfDayOfMonthBetweenDates(LocalDate startDate, LocalDate endDate, int dayOfMonth) {
long result = -1;
if (startDate != null && endDate != null && dayOfMonth > 0 && dayOfMonth < 32) {
result = 0;
LocalDate startDay = getDayInCurrentMonth(startDate, dayOfMonth);
// add one day as end date is exclusive
// add + 1 to cover higher possibilities (month and a half or half month or so)
long totalMonths = ChronoUnit.MONTHS.between(startDate, endDate.plusDays(1)) + 2;
for (int i = 0; i < totalMonths; i++) {
if ((!startDay.isBefore(startDate) && startDay.isBefore(endDate)) || startDay.equals(startDate) || startDay.equals(endDate)) {
result++;
}
startDay = getDayInCurrentMonth(startDay.plusMonths(1), dayOfMonth);
}
}
return result;
}
private LocalDate getDayInCurrentMonth(LocalDate startDate, int dayOfMonth) {
LocalDate dayOfThisMonth;
try {
dayOfThisMonth = startDate.withDayOfMonth(dayOfMonth);
} catch (DateTimeException e) {
// handle cases where current month does not contain the given day (example 30 in Feb)
dayOfThisMonth = startDate.withDayOfMonth(startDate.lengthOfMonth());
}
return dayOfThisMonth;
}