7

我需要得到前一个工作日:

public DateTime GetPreviousWorkDay(DateTime date)
{
    DateTime prevDay = date.AddDays(-1);
    bool isHoliday = IsHoliday(prevDay);
    while (isHoliday || prevDay.DayOfWeek == DayOfWeek.Saturday || prevDay.DayOfWeek == DayOfWeek.Sunday)
    {
        prevDay = prevDay.AddDays(-1);
        isHoliday = IsHoliday(prevDay);
    }
    return prevDay;
}

这种方法安全吗?会不会是无限循环?有没有更简单的方法?

4

1 回答 1

27

为了使逻辑更清晰,我提取了IsWeekend方法并删除了不必要的临时变量。简单的do..while循环将完成这项工作:

public DateTime PreviousWorkDay(DateTime date)
{
    do 
    {        
        date = date.AddDays(-1);        
    } 
    while(IsHoliday(date) || IsWeekend(date));

    return date;
}

private bool IsWeekend(DateTime date)
{
    return date.DayOfWeek == DayOfWeek.Saturday ||
           date.DayOfWeek == DayOfWeek.Sunday;
}   
于 2013-10-03T14:31:22.450 回答