Search code examples
mathdate-arithmetic

Find the number of week rows in a month


Given the start day (Wednesday = 4), and the number of days in a month (31), what is an elegant way to find the number of week rows a calendar of the month would require?

For the current month (startDay = 4, daysInMonth = 31), it would be 5. But if daysInMonth = 33, it would be 6 rows.

This doesn't quite work:

int numRows = (startDay+daysInMonth)/daysInWeek;
if ((startDay+daysInMonth) % daysInWeek != 0) {
    numRows++;
}

Solution

  • Just change to

    int numRows = (startDay + daysInMonth - 1) / daysInWeek;
    if ((startDay+daysInMonth - 1) % daysInWeek != 0) {
        numRows++;
    }
    

    and you should get the correct result. EDIT: just to slightly expand on it : you have the right idea, you just forgot to account for the fact that the offset for day 1 is 0, not 1.