In Java, get all weekend dates in a given month
Here is a rough version with comments describing the steps:
// create a Calendar for the 1st of the required month
int year = 2010;
int month = Calendar.JANUARY;
Calendar cal = new GregorianCalendar(year, month, 1);
do {
// get the day of the week for the current day
int day = cal.get(Calendar.DAY_OF_WEEK);
// check if it is a Saturday or Sunday
if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
// print the day - but you could add them to a list or whatever
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
// advance to the next day
cal.add(Calendar.DAY_OF_YEAR, 1);
} while (cal.get(Calendar.MONTH) == month);
// stop when we reach the start of the next month
java.time
You can use the Java 8 stream and the java.time package. Here an IntStream
from 1
to the number of days in the given month is generated. This stream is mapped to a stream of LocalDate
in the given month then filtered to keep Saturday's and Sunday's.
import java.time.DayOfWeek;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.util.stream.IntStream;
class Stackoverflow{
public static void main(String args[]){
int year = 2010;
Month month = Month.JANUARY;
IntStream.rangeClosed(1,YearMonth.of(year, month).lengthOfMonth())
.mapToObj(day -> LocalDate.of(year, month, day))
.filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY ||
date.getDayOfWeek() == DayOfWeek.SUNDAY)
.forEach(date -> System.out.print(date.getDayOfMonth() + " "));
}
}
We find the same result as the first answer (2 3 9 10 16 17 23 24 30 31).