我有当前日期和一个常数,它告诉一周从哪一天开始。我想根据该常数获取一周的开始日期。如果我将一周的第一天硬编码到星期一(或其他任何时间),那么这很简单。但是一周的第一天一直在变化。所以不想改代码,每次第一天都要改。
这是我用java的日历尝试过的:
public static Date getLastWeekdayDate()
{
Calendar calendar = new GregorianCalendar();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int daysToSubtractFromCurrentDate = 0;
switch (dayOfWeek)
{
case Calendar.WEDNESDAY:
daysToSubtractFromCurrentDate = 4;
break;
case Calendar.THURSDAY:
daysToSubtractFromCurrentDate = 5;
break;
case Calendar.FRIDAY:
daysToSubtractFromCurrentDate = 6;
break;
case Calendar.SATURDAY:
daysToSubtractFromCurrentDate = 0;
break;
case Calendar.SUNDAY:
daysToSubtractFromCurrentDate = 1;
break;
case Calendar.MONDAY:
daysToSubtractFromCurrentDate = 2;
break;
case Calendar.TUESDAY:
daysToSubtractFromCurrentDate = 3;
break;
}
calendar.add(Calendar.DATE, -daysToSubtractFromCurrentDate);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
我想得到一周的开始日期。上面的函数返回一周的第一天,一周的开始日期被硬编码为星期六。每当关于一周开始日的要求发生变化时,我都必须更改代码。