13

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

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

4

4 回答 4

21

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

// 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
于 2010-07-17T17:24:16.567 回答
14

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() + " "));
    }
}

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

于 2015-06-15T13:03:22.083 回答
3
于 2016-10-07T20:34:57.097 回答
2

你可以这样尝试:

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());
      }
}
于 2016-10-07T11:34:06.763 回答