Working with date: print all dates in a given range

Asked

Viewed 711 times

1

I am struggling with simple implementation. I need to receive the amount of days, excluding Saturdays and Sundays, from a certain date range. I tried using Calendar because I can set the day(date), month and year and use the calendar.get(Calendar.DAY_OF_WEEK) that return me the day of the whole week.

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 code above, but when, for example, the initial month is shorter but the day is not, it does not do what it should do.

  • I did not understand the phrase: "the initial month is shorter but the day is not". I could explain better?

1 answer

1

The problem lies here

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

In case you should make it run until the last day of the month and 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 the case was what I could understand that you want to stop on the day, month and year stipulated, and in this case lastDayMonth should be set to take the last day of each month in the case just before starting this last.

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

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

Also it is important to remember that when it passes 1 year you must reset the month counter and return to 1, this is whenever Month > 12 = 1 ai you can in this idea keep changing the month without errors.

I hope this is your doubt.

Att. Thiago Prado

Browser other questions tagged

You are not signed in. Login or sign up in order to post.