您可以通过将一周中的当前日期与目标日期进行比较来计算要减去多少天,以防万一为负:
static DateTime GetDate(DateTime now, DayOfWeek dayOfWeek)
{
// Number of days to subtract, e.g. 1 for "today is Friday, we want Thursday"
// The ((...) + 7) % 7 part is to handle wrap-around for negative values.
int daysDifference = ((now.DayOfWeek - dayOfWeek) + 7) % 7;
return now.AddDays(-daysDifference);
}
或者使用Noda Time(我的日期/时间 API,它允许更清晰地表示“只是一个日期”等):
static LocalDate GetDate(LocalDate today, IsoDayOfWeek dayOfWeek)
{
return today.IsoDayOfWeek == dayOfWeek ? today : today.Previous(dayOfWeek);
}