查找给定日期范围内的所有星期六和星期日
我想从给定的日期范围内获取所有星期六和星期日...
我的输入是
开始日期: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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,如果可以的话,我建议使用 Joda Time。它是一种比 Java 内置的日期和时间 API 更好的日期和时间 API。
其次,除非您真的担心效率,否则我个人会采用极其简单但有点浪费的方法,即简单地迭代该时间段内的每一天,并包括那些落在正确日期的日期。在增加一天和增加六天之间交替肯定会更有效,但更难改变。
示例代码:
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:
我建议您查看此 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.
我认为,您可以使用以下方式 - 它非常简单,并且不需要使用其他库。
取工作日编号(周一 = 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.
这是完整的示例。
如果我们可以做得更好,请提出建议。
Here is the complete example.
Please do suggest if we can make it better.
我假设您的开始日期和结束日期以毫秒为单位。循环遍历日期并检查日期是
'Saturday'
还是'Sunday'
。下面我返回总数。给定日期范围内的周六和周日。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.