我需要找到给定月份和给定年份的所有周末日期。
例如:对于 01(月)、2010(年),输出应为:2、3、9、10、16、17、23、24、30、31,所有周末日期。
这是一个粗略的版本,其中包含描述步骤的注释:
// 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 8 流和java.time 包。这里生成IntStream
从1
到给定月份的天数。此流映射到LocalDate
给定月份的流,然后过滤以保留周六和周日的流。
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() + " "));
}
}
我们发现与第一个答案相同的结果 (2 3 9 10 16 17 23 24 30 31)。
你可以这样尝试:
int year=2016;
int month=10;
calendar.set(year, 10- 1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
ArrayList<Date> sundays = new ArrayList<Date>();>
for (int d = 1; d <= daysInMonth; d++) {
calendar.set(Calendar.DAY_OF_MONTH, d);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek==Calendar.SUNDAY) {
calendar.add(Calendar.DATE, d);
sundays.add(calendar.getTime());
}
}