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

编程入门 行业动态 更新时间:2024-10-27 09:45:08
本文介绍了查找指定日期范围内的所有星期六和星期日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

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

本文发布于:2023-05-24 12:35:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/226666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内   星期日   星期   日期   六和

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!