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

2022-09-04 05:39:57

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

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


答案 1

这是一个粗略的版本,带有描述步骤的注释:

// 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

答案 2

java.time

您可以使用 Java 8 流java.time 包。这里生成一个 IntStream 从 到给定月份的天数。此流映射到给定月份的 LocalDate 流,然后进行过滤以保留星期六和星期日的流。1

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)。