views:

124

answers:

4

I want to calculate Saturday's and Sunday's in a date range? How can i ?

+2  A: 

iterate in days and so :

Calendar date ;//initiate with your date
int day = date.get(Calendar.DAY_OF_WEEK); // 1=Sunday , 2=Monday , ...

check the day:

if(day == 1 || day == 7)
{
    //add to your list this **date** (for example List<Calender>
}

and so on.

SjB
what if i need to know days in 2 years ?
Zeeshan
iterate each day of 2 year and check with if that added in edit
SjB
I would use `Calendar.SATURDAY` and `Calendar.SUNDAY` instead of the numbers.
Carlos Heuberger
@Carlos Heuberger: That's right. more readable :-)
SjB
A: 

Joda example:

dateTime.dayOfWeek().get() == DateTimeConstants.SATURDAY;
Kees de Kooter
... this is pretty incomplete, it just shows a test for a single date
Andreas_D
Yup. I SO is showing a trend towards 1-sentence-answers lately, which is not good.
seanizer
And a trend of 1 sentence questions. Won't answer those anymore.
Kees de Kooter
@Andreas_D I supposed the OP is able to write the surrounding code himself.
Kees de Kooter
A: 

Find 1st Saturday&Sunday in the range, then Calendar.add(Calendar.DATE, 7) to get Saturdays&Sundays until end of range. It's faster than checking each day in the range.

卢声远 Shengyuan Lu
-1 plus seven? not integer
Pureth
@Pureth: actually you can add days to a date using JODA
pablochan
If you'd replace your +7 statement with the `Calendar.add(Calendar.DATE, 7)` method invocation you probably have in mind, the downvotes may vanish.
seanizer
@pablochan: also you can add with my framework!
Pureth
@seanizer: Thanks! You said what I mean:)
卢声远 Shengyuan Lu
A: 
// Initialise two dates at midnight
Calendar startDate = Calendar.getInstance();
startDate.set(startYear, startMonth - 1, startDay, 0, 0, 0);
Calendar endDate = Calendar.getInstance();
endDate.set(endYear, endMonth - 1, endDay, 0, 0, 0);

// Calculate number of full weeks between two dates
long startDateMillis = startDate.getTimeInMillis();
long endDateMillis = endDate.getTimeInMillis();
long weeksInRange = (endDateMillis - startDateMillis) / 1000 / 60 / 60 / 24 / 7;
// Multiply by 2 to get weekend days in range
long weekendDaysInRange = weeksInRange * 2;

// Add on extra days in final incomplete week
int startDayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);
int endDayOfWeek = endDate.get(Calendar.DAY_OF_WEEK);
if (endDayOfWeek == Calendar.SATURDAY) {
    if (startDayOfWeek != Calendar.SATURDAY) {
        weekendDaysInRange++;
    }
} else {
    if (startDayOfWeek == Calendar.SATURDAY) {
        weekendDaysInRange++;
    } else if (startDayOfWeek != Calendar.SUNDAY) {
        weekendDaysInRange += 2;
    }
}
lins314159
To those who marked this down, are you able to comment on what's wrong?
lins314159