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
2010-08-27 11:35:15
what if i need to know days in 2 years ?
Zeeshan
2010-08-27 11:46:02
iterate each day of 2 year and check with if that added in edit
SjB
2010-08-27 11:48:43
I would use `Calendar.SATURDAY` and `Calendar.SUNDAY` instead of the numbers.
Carlos Heuberger
2010-08-27 12:22:25
@Carlos Heuberger: That's right. more readable :-)
SjB
2010-08-27 12:30:27
A:
Joda example:
dateTime.dayOfWeek().get() == DateTimeConstants.SATURDAY;
Kees de Kooter
2010-08-27 11:37:58
Yup. I SO is showing a trend towards 1-sentence-answers lately, which is not good.
seanizer
2010-08-27 11:53:35
@Andreas_D I supposed the OP is able to write the surrounding code himself.
Kees de Kooter
2010-08-27 15:27:47
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
2010-08-27 11:42:32
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
2010-08-27 11:52:01
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
2010-08-27 12:07:30
To those who marked this down, are you able to comment on what's wrong?
lins314159
2010-08-28 03:53:53