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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3272454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:05:56  来源:igfitidea点击:

In Java, get all weekend dates in a given month

javadateweekend

提问by usman

I need to find all the weekend dates for a given month and a given year.

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

Eg: For 01(month), 2010(year), the output should be : 2,3,9,10,16,17,23,24,30,31, all weekend dates.

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

回答by mikej

Here is a rough version with comments describing the steps:

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

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

回答by Ortomala Lokni

java.time

时间

You can use the Java 8 streamand the java.time package. Here an IntStreamfrom 1to the number of days in the given month is generated. This stream is mapped to a stream of LocalDatein the given month then filtered to keep Saturday's and Sunday's.

您可以使用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() + " "));
    }
}

We find the same result as the first answer (2 3 9 10 16 17 23 24 30 31).

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

回答by Basil Bourque

The Answer by Lokniappears to be correct, with bonus points for using Streams.

Lokni答案似乎是正确的,使用 Streams 可以获得奖励积分。

EnumSet

EnumSet

My suggestion for improvement: EnumSet. This class is an extremely efficient implementation of Set. Represented internally as bit vectors, they are fast to execute and taking very little memory.

我的改进建议:EnumSet。此类是Set. 在内部表示为位向量,它们执行速度快且占用内存很少。

Using an EnumSetenables you to soft-codethe definition of the weekend by passing in a Set<DayOfWeek>.

使用EnumSet让您的软码周末的定义,通过传递Set<DayOfWeek>

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

Demo using the old-fashioned syntax without Streams. You could adapt Lokni's answer's codeto use an EnumSetin a similar manner.

使用没有 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<LocalDate> 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

You can also make use of the TemporalAdjusterinterface which provides for classes that manipulate date-time values. The TemporalAdjustersclass (note the plural s) provides several handy implementations.

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

The ThreeTen-Extraproject provides classes working with java.time. This includes a TemporalAdjusterimplementation, Temporals.nextWorkingDay().

ThreeTen-EXTRA项目提供java.time工人阶级。这包括一个TemporalAdjuster实现,Temporals.nextWorkingDay().

You can write your own implementation to do the opposite, a nextWeekendDaytemporal adjuster.

您可以编写自己的实现来做相反的事情,即nextWeekendDay时间调整器。



About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by VinayaK

You could try like this:

你可以这样尝试:

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