我想从指定日期范围获取所有星期六和星期日...
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; } }更多推荐
查找指定日期范围内的所有星期六和星期日
发布评论