获取上一个工作日

时间:2013-10-03 14:21:01

标签: c# datetime

我需要上一个工作日:

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;
}

这种方法安全吗?它可以是无限循环吗?有更简单的方法吗?

1 个答案:

答案 0 :(得分:19)

为了使逻辑更清晰,我提取了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;
}