查找给定日期范围内的所有星期六和星期日

发布于 2024-12-09 02:06:04 字数 147 浏览 0 评论 0原文

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

我的输入是

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

现在搜索介于给定开始日期和结束日期之间的日期,并且日期将为星期六或星期日。

请建议...

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

my inputs are

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.

Please Suggest...

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

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

发布评论

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

评论(5

作业与我同在 2024-12-16 02:06:04

首先,如果可以的话,我建议使用 Joda Time。它是一种比 Java 内置的日期和时间 API 更好的日期和时间 API。

其次,除非您真的担心效率,否则我个人会采用极其简单但有点浪费的方法,即简单地迭代该时间段内的每一天,并包括那些落在正确日期的日期。在增加一天和增加六天之间交替肯定会更有效,但更难改变。

示例代码:

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

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.

Sample code:

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;
    }                                            
}
ゝ偶尔ゞ 2024-12-16 02:06:04

我建议您查看 RFC-2445 Java 开源库。您可以创建每周重复规则,并在周六和周日重复,然后迭代指定的时间段以获取所有日期。

I recommend to take a look at this RFC-2445 Java open-source library. You can create a weekly recurrence rule with repeating on Sat and Sun, then iterate over the specified period to get all dates.

孤云独去闲 2024-12-16 02:06:04

我认为,您可以使用以下方式 - 它非常简单,并且不需要使用其他库。

取工作日编号(周一 = 1,周日 = 7)。然后 - 选择新的开始日期,即第一个星期日 ->它是开始日期 + (7 - weekdayNum)。通过相同的算法,您可以从间隔中获取上周日(我认为通过减去 EndDate - weekdayNum - 1)。现在您可以进入 for 循环遍历所有发生的情况(使用增量步骤 7)。或者,如果您想要特定的发生时间,例如第三个星期日,您可以简单地执行 newStartDate + 3 * 7。

我希望这很清楚。我不确定数字是否正确。希望这有助于理解问题。

I think, you can use following way - it's really simple and you don't need to use other libraries.

Take weekday number (for Monday = 1, Sunday = 7). Then - choose new start date, which is first Sunday occurence -> it is startDate + (7 - weekdayNum). By the same algorithm, you can take last Sunday from interval (by substracting EndDate - weekdayNum - 1, I think). And now you can go in for loop through all occurences (use incremental step 7). Or if you want specific occurence, e.g. 3rd sunday, you can simply do newStartDate + 3 * 7.

I hope, this is clear. I'm not sure, if numbers are correct. Hope this helps for understanding the problem.

无边思念无边月 2024-12-16 02:06:04

这是完整的示例。
如果我们可以做得更好,请提出建议。

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 
 * @author varun.vishwakarma
 */
public class FindWeekendsInDateRange {
static HashMap<Integer, String> daysOfWeek=null;


static {
	daysOfWeek = new HashMap<Integer, String>();
	daysOfWeek.put(new Integer(1), "Sun");
	daysOfWeek.put(new Integer(2), "Mon");
	daysOfWeek.put(new Integer(3), "Tue");
	daysOfWeek.put(new Integer(4), "Wed");
	daysOfWeek.put(new Integer(5), "Thu");
	daysOfWeek.put(new Integer(6), "Fri");
	daysOfWeek.put(new Integer(7), "Sat");
}

/**
 * 
 * @param from_date 
 * @param to_date
 * @return 
 */
public static List<Date>  calculateWeekendsInDateReange(Date fromDate, Date toDate) {
	List<Date> listOfWeekends = new ArrayList<Date>();
		Calendar from = Calendar.getInstance();
		Calendar to = Calendar.getInstance();
		from.setTime(fromDate);
		to.setTime(toDate);
		while (from.getTimeInMillis() < to.getTimeInMillis()) {
			if (daysOfWeek.get(from.get(Calendar.DAY_OF_WEEK)) == "Sat") {
				Date sat = from.getTime();
				listOfWeekends.add(sat);
			} else if (daysOfWeek.get(from.get(Calendar.DAY_OF_WEEK)) == "Sun") {
				Date sun = from.getTime();
				listOfWeekends.add(sun);
			}
			from.add(Calendar.DAY_OF_MONTH, 1);
		}
	return listOfWeekends;
}
public static void main(String[] args) {
	String fromDate = "7-Oct-2019";
	String toDate = "25-Oct-2019";
	System.out.println(FindWeekendsInDateRange.calculateWeekendsInDateReange(new Date(fromDate), new Date(toDate)));


}

}

Here is the complete example.
Please do suggest if we can make it better.

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 
 * @author varun.vishwakarma
 */
public class FindWeekendsInDateRange {
static HashMap<Integer, String> daysOfWeek=null;


static {
	daysOfWeek = new HashMap<Integer, String>();
	daysOfWeek.put(new Integer(1), "Sun");
	daysOfWeek.put(new Integer(2), "Mon");
	daysOfWeek.put(new Integer(3), "Tue");
	daysOfWeek.put(new Integer(4), "Wed");
	daysOfWeek.put(new Integer(5), "Thu");
	daysOfWeek.put(new Integer(6), "Fri");
	daysOfWeek.put(new Integer(7), "Sat");
}

/**
 * 
 * @param from_date 
 * @param to_date
 * @return 
 */
public static List<Date>  calculateWeekendsInDateReange(Date fromDate, Date toDate) {
	List<Date> listOfWeekends = new ArrayList<Date>();
		Calendar from = Calendar.getInstance();
		Calendar to = Calendar.getInstance();
		from.setTime(fromDate);
		to.setTime(toDate);
		while (from.getTimeInMillis() < to.getTimeInMillis()) {
			if (daysOfWeek.get(from.get(Calendar.DAY_OF_WEEK)) == "Sat") {
				Date sat = from.getTime();
				listOfWeekends.add(sat);
			} else if (daysOfWeek.get(from.get(Calendar.DAY_OF_WEEK)) == "Sun") {
				Date sun = from.getTime();
				listOfWeekends.add(sun);
			}
			from.add(Calendar.DAY_OF_MONTH, 1);
		}
	return listOfWeekends;
}
public static void main(String[] args) {
	String fromDate = "7-Oct-2019";
	String toDate = "25-Oct-2019";
	System.out.println(FindWeekendsInDateRange.calculateWeekendsInDateReange(new Date(fromDate), new Date(toDate)));


}

}

煮茶煮酒煮时光 2024-12-16 02:06:04

我假设您的开始日期和结束日期以毫秒为单位。循环遍历日期并检查日期是'Saturday' 还是'Sunday'。下面我返回总数。给定日期范围内的周六和周日。

private int totalWeekendDays(long start, long end)
{
    int result=0;
    long dayInMS = TimeUnit.DAYS.toMillis(1);
    for (long i = start; i<=end; i = i + dayInMS)
    {
        String dayOfTheWeek = (String) DateFormat.format("EEEE", i);
        if (dayOfTheWeek.equals("Sunday")||dayOfTheWeek.equals("Saturday"))
        {
            result = result+1;
        }
    }
    return result;
}

I'm assuming your start and end dates are given in milliseconds. Loop through the dates and check whether days are 'Saturday' or 'Sunday'. Below I'm returning the total no. of Saturday and Sunday in given date range.

private int totalWeekendDays(long start, long end)
{
    int result=0;
    long dayInMS = TimeUnit.DAYS.toMillis(1);
    for (long i = start; i<=end; i = i + dayInMS)
    {
        String dayOfTheWeek = (String) DateFormat.format("EEEE", i);
        if (dayOfTheWeek.equals("Sunday")||dayOfTheWeek.equals("Saturday"))
        {
            result = result+1;
        }
    }
    return result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文