获取给定当前日期和周开始的周开始和结束日期 [英] 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;
现在,我们可以缩短所有这些到两行:
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屋!