我有一个要求,我想根据今天的日期计算某一天的最后日期。例如,我有一个方法
DateTime GetDate(DateTime now, DayOfWeek dayOfWeek)
{
//Logic goes here
}
例如
条件:
答案 0 :(得分:4)
您可以通过将当前星期几与目标日期进行比较来计算减去天数,如果它是负数,则可以计算:
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);
}
答案 1 :(得分:0)
确定,
DateTime GetDate(DateTime now, DayOfWeek dayOfWeek)
{
var day = new TimeSpan(1, 0, 0, 0);
var result = now;
while(result.DayOfWeek != dayOfWeek)
{
result = result.Substract(day)
}
return result;
}
答案 2 :(得分:0)
private static DateTime GetDate(DateTime todayDate, DayOfWeek dayofweek)
{
while (todayDate.DayOfWeek != dayofweek)
{
todayDate = todayDate.AddDays(-1);
}
return todayDate;
}