在Java中,获取给定月份的所有周末日期

usm*_*man 13 java date weekend

我需要查找给定月份和给定年份的所有周末日期.

例如:对于01(月),2010(年),输出应为:2,3,9,10,16,17,23,24,30,31,所有周末日期.

mik*_*kej 22

这是一个粗略的版本,其中包含描述步骤的注释:

// 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
Run Code Online (Sandbox Code Playgroud)


Ort*_*kni 12

java.time

您可以使用Java 8流java.time包.这里生成了IntStream1给定月份的天数到天数.此流将映射到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() + " "));
    }
}
Run Code Online (Sandbox Code Playgroud)

我们找到与第一个答案相同的结果(2 3 9 10 16 17 23 24 30 31).