欢迎访问宙启技术站
智能推送

Java函数实现获取指定日期范围内的所有周末日期

发布时间:2023-06-25 11:17:54

在Java中,实现获取指定日期范围内的所有周末日期可以使用Calendar类和Date类来实现。

首先,我们需要获取指定日期范围内的所有日期。可以通过设置起始日期和结束日期,以及日历的实例来获取。代码如下:

public static List<Date> getDatesBetween(Date startDate, Date endDate) {
    List<Date> datesInRange = new ArrayList<>();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
 
    while (calendar.getTime().before(endDate)) {
        Date result = calendar.getTime();
        datesInRange.add(result);
        calendar.add(Calendar.DATE, 1);
    }
 
    return datesInRange;
}

这段代码会返回起始日期和结束日期之间的所有日期。接下来,我们要筛选出所有的周末日期。可以通过判断每个日期的星期几来实现。如果是周六或周日,则认为是周末日期。代码如下:

public static List<Date> getWeekendDates(Date startDate, Date endDate) {
    List<Date> weekendDates = new ArrayList<>();
    List<Date> datesInRange = getDatesBetween(startDate, endDate);
 
    for (Date date : datesInRange) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
 
        if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
            weekendDates.add(date);
        }
    }
 
    return weekendDates;
}

这段代码将使用上面我们定义的 getDatesBetween 方法来获取指定日期范围内的所有日期。然后对于每个日期,获取日历实例,并检查日期的星期几。如果是周六或周日,则将该日期添加到返回列表中。

最后,我们再次使用上面定义的 getDatesBetween 方法获取指定日期范围内的所有日期,并使用上面定义的 getWeekendDates 方法获取所有周末日期。代码如下:

public static void main(String[] args) {
    Date startDate = new Date(121, 11, 1); // 2021-12-01
    Date endDate = new Date(122, 0, 1); // 2022-01-01
 
    List<Date> datesInRange = getDatesBetween(startDate, endDate);
    List<Date> weekendDates = getWeekendDates(startDate, endDate);
 
    System.out.println("所有日期:" + datesInRange);
    System.out.println("所有周末日期:" + weekendDates);
}

这段代码会输出指定日期范围内的所有日期和所有周末日期。可以根据需要对输出进行格式化等操作。

总结:

在Java中,实现获取指定日期范围内的所有周末日期可以通过获取日期范围内的所有日期,并检查每个日期是否为周末日期来实现。代码实现简单,使用Calendar类和Date类即可实现。