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 パッケージを使用できます。ここでは、指定された月の日数IntStreamからto が生成されます。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)。

于 2015-06-15T13:03:22.083 に答える