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

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

例如:对于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.time

您可以使用Java 8流和java.time包 。 这里IntStream1到给定月份的天数的IntStream 。 此流将在给定月份映射到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)。

Lokni的答案似乎是正确的,使用Streams有奖励积分。

EnumSet

我的改进建议: EnumSet 。 这个类是Set一个非常有效的实现。 它们在内部表示为位向量,它们执行速度快,占用的内存很少。

使用EnumSet您可以通过传入Set对周末的定义进行软编码 。

 Set dows = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ); 

使用没有Streams的老式语法进行演示。 你可以调整Lokni的答案代码 ,以类似的方式使用EnumSet

 YearMonth ym = YearMonth.of( 2016 , Month.JANUARY ) ; int initialCapacity = ( ( ym.lengthOfMonth() / 7 ) + 1 ) * dows.size() ; // Maximum possible weeks * number of days per week. List dates = new ArrayList<>( initialCapacity ); for (int dayOfMonth = 1; dayOfMonth <= ym.lengthOfMonth() ; dayOfMonth ++) { LocalDate ld = ym.atDay( dayOfMonth ) ; DayOfWeek dow = ld.getDayOfWeek() ; if( dows.contains( dow ) ) { // Is this date *is* one of the days we care about, collect it. dates.add( ld ); } } 

TemporalAdjuster

您还可以使用TemporalAdjuster接口,该接口提供操作日期时间值的类。 TemporalAdjusters类(注意复数s )提供了几个方便的实现。

ThreeTen-Extra项目提供了使用java.time的类。 这包括TemporalAdjuster实现, Temporals.nextWorkingDay()

您可以编写自己的实现来执行相反的操作,即nextWeekendDay时间调整器。

你可以尝试这样:

 int year=2016; int month=10; calendar.set(year, 10- 1, 1); int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); ArrayList sundays = new ArrayList();> 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()); } }