查找指定日期范围内的所有星期六和星期日 [英] Find all Saturday and Sunday from given date range

查看:258
本文介绍了查找指定日期范围内的所有星期六和星期日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从指定日期范围获取所有星期六和星期日...

I want to take all Saturday and Sunday from given date range...

我的输入是

开始日期:01/01/2011
结束日期:01/01/2012

Start Date : 01/01/2011 End Date : 01/01/2012

现在在指定开始日期和结束日期之间的搜索日期,

now search date which is in between given start date and end date and day would be Saturday or Sunday.

推荐答案

p>首先,我建议您尽可能使用 Joda时间

Firstly, I'd recommend using Joda Time if you possibly can. It's a much better date and time API than the one built into Java.

其次,除非你真的担心效率,否则我会个人的去寻求一种简单但是有点浪费的方法,在时间段内每天都进行简单的迭代,包括那些落在正确的日子。

Secondly, unless you're really worried about efficiency I would personally go for the incredibly-simple-but-somewhat-wasteful approach of simply iterating over every day in the time period, and including those which fall on the right days. Alternating between adding one day and adding six days would certainly be more efficient, but harder to change.

示例代码:

import java.util.*;
import org.joda.time.*;

public class Test
{
    public static void main(String[] args)
    {
        List<LocalDate> dates = getWeekendDates
            (new LocalDate(2011, 1, 1), new LocalDate(2011, 12, 1));
        for (LocalDate date : dates)
        {
            System.out.println(date);
        }
    }

    private static List<LocalDate> getWeekendDates
        (LocalDate start, LocalDate end)
    {
        List<LocalDate> result = new ArrayList<LocalDate>();
        for (LocalDate date = start;
             date.isBefore(end);
             date = date.plusDays(1))
        {
            int day = date.getDayOfWeek();
            // These could be passed in...
            if (day == DateTimeConstants.SATURDAY ||
                day == DateTimeConstants.SUNDAY)
            {
                result.add(date);
            }
        }
        return result;
    }                                            
}

这篇关于查找指定日期范围内的所有星期六和星期日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆