Working with date: print all dates in a given range

1

I'm struggling with simple implementation. I need to receive the amount of days, taking Saturdays and Sundays, from a certain range of dates. I tried to use Calendar because I can set the day (date), month and year and use calendar.get(Calendar.DAY_OF_WEEK) to return the day of the week in full.

for (int i = firstYear; i <= currentYear; i++) {
    for (int j = firstMonth; j <= currentMonth; j++) {
        for (int d = firstDay; d <= currentDay; d++) {
            calendar.clear();
            calendar.set(i, j-1, d); // LEMRAR QUE O MÊS COMEÇA COM 0 E NÃO COM 1
            if((calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY)){
                count++;
                }
            }
        }
    }

The closest I got was the above code, but when, for example, the initial month is shorter but the day is not, it does not do what it should.

    
asked by anonymous 06.08.2014 / 02:47

1 answer

1

The problem is here

for (int d = firstday; d <= currentDay; d++)

In case you should make it run until the last day of the month and inside make an if that check if the day you want corresponds to the month and make a break .

for (int d = firsDay; d <= lastDayMonth; d++)
{
    if ( currentYear == i && currentMonth == j && currentDay == d)
        break;
}

In this case, I understand that you want to stop the stipulated day, month and year, and in this case lastDayMonth must be configured to take the last day of each month in the case just before the last foray.

Detail that I forgot to put earlier, the days should always start from 1 if you want to print every day at the interval, when you put firstday you complicate the system, since every day start from day 1.

Second detail you can start day a from day 5 but then to next month you should zero and put for day 1.

It's also important to remember that when you spend 1 year you should reset the month counter and return to 1, this is where month > 12 = 1 ai you can get this idea to change the month without errors.

I hope this is your doubt.

Att. Thiago Prado

    
06.08.2014 / 02:59