获取当前日期和周开始的星期开始和结束日期 [英] Get the week start and end date given a current date and week start
问题描述
如果可能,我更喜欢下面的场景中的joda或非joda解决方案。
If possible I would prefer a joda or non-joda solution for the scenario below
让我们说如果我的周从02/05/2012开始,给定的当前日期是02/22/2011。我需要计算给定当前日期的周开始和结束日期。所以我的解决方案应该是从02/19开始,周末是02/25。
为了简单起见,我已经将我的周开始于02/05/2011,但可能是任何一天可能,我的周总是有7天。
Lets say if my week starts on 02/05/2012 and the given current date is 02/22/2011. I need to calculate the week start and end date for the given current date. So my solution should have the week start as 02/19 and week ends at 02/25. For simplicity, I have set my week start here as 02/05/2011 but it could be any day potentially and my week always has 7 days.
我现在的代码在下面,但似乎没有像预期的那样工作。
My existing code is below but doesnt seem to work as expected.
public Interval getWeekInterval(Date calendarStartDate, Date date)
{
Calendar sDate = Calendar.getInstance();
sDate.setTime(getMidnightDate(calendarStartDate));
Calendar eDate = Calendar.getInstance();
eDate.setTime(date);
Calendar weekStartDate = (Calendar) sDate.clone();
logger.debug("Date:" + sDate.getTime());
while (sDate.before(eDate)) {
weekStartDate = sDate;
sDate.add(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
}
return new Interval(weekStartDate.getTime(), sDate.getTime());
}
推荐答案
尝试这个(伪代码):
// How many days gone after reference date (a known week-start date)
daysGone = today - referenceDate;
// A new week starts after each 7 days
dayOfWeek = daysGone % 7;
// Now, we know today is which day of the week.
// We can find start & end days of this week with ease
weekStart = today - dayOfWeek;
weekEnd = weekStart + 6;
现在,我们可以将缩短到两行: p>
Now, we can shorten all of this to two lines:
weekStart = today - ((today - referenceDate) % 7);
weekEnd = weekStart + 6;
请注意,我们减去日期值,如整数,以显示算法。你必须正确地编写你的java代码。
Note that we subtracted date values like integers to show algorithm. You have to write your java code properly.
这篇关于获取当前日期和周开始的星期开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!