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

发布于 2024-09-10 11:08:54 字数 97 浏览 3 评论 0 原文

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

网名女生简单气质 2024-09-17 11:08:54

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

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

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
べ映画 2024-09-17 11:08:54

java.time

您可以使用 Java 8 流< /a> 和 java.time 包。这里有一个 IntStream< /a> 生成从 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)。

java.time

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

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

清风无影 2024-09-17 11:08:54

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

EnumSet

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

使用 EnumSet 使您能够软编码通过传入 Set 来设置周末。

Set<DayOfWeek> 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<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 接口,提供操作日期时间值的类。 TemporalAdjusters< /a> 类(注意复数 s)提供了几种方便的实现。

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

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


关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & ; SimpleDateFormat

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

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

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

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time 。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeek<代码>YearQuarter,以及更多

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

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.

Using an EnumSet enables you to soft-code the definition of the weekend by passing in a 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 code to use an EnumSet in a similar manner.

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

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

The ThreeTen-Extra project provides classes working with java.time. This includes a TemporalAdjuster implementation, Temporals.nextWorkingDay().

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


About java.time

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

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project 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.

蒗幽 2024-09-17 11:08:54

你可以这样尝试:

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

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());
      }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文