如何减去工作日?

时间:2016-09-26 18:33:11

标签: c# datetime asp.net-mvc-5

如何在“添加工作日”中基于此减去C#中的工作日:

    public static DateTime AddBusinessDays(DateTime date, int days = 5)
    {
        if (days < 0)
        {
            throw new ArgumentException("days cannot be negative", "days");
        }

        if (days == 0) return date;

        if (date.DayOfWeek == DayOfWeek.Saturday)
        {
            date = date.AddDays(2);
            days -= 1;
        }
        else if (date.DayOfWeek == DayOfWeek.Sunday)
        {
            date = date.AddDays(1);
            days -= 1;
        }

        date = date.AddDays(days / 5 * 7);
        int extraDays = days % 5;

        if ((int)date.DayOfWeek + extraDays > 5)
        {
            extraDays += 2;
        }

        return date.AddDays(extraDays);

    }

这不能带负数,所以需要另外一个专门用于减去工作日。

编辑:该“重复”问题是衡量工作日的两个日期之间的差异。我只想要一个开始日期,以及减去得出结果的天数。 这可以作为一个函数完成,而不是像上面为AddDays看到的那样作为扩展。

如上所示,没有循环的方法将是最有效的。

1 个答案:

答案 0 :(得分:0)

See this Answer

(为方便起见,下面重复链接的答案)

  

使用Fluent DateTime:

var now = DateTime.Now;
var dateTime1 = now.AddBusinessDays(3);
var dateTime2 = now.SubtractBusinessDays(5);
  

内部代码如下

/// <summary>
/// Adds the given number of business days to the <see cref="DateTime"/>.
/// </summary>
/// <param name="current">The date to be changed.</param>
/// <param name="days">Number of business days to be added.</param>
/// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns>
public static DateTime AddBusinessDays(this DateTime current, int days)
{
    var sign = Math.Sign(days);
    var unsignedDays = Math.Abs(days);
    for (var i = 0; i < unsignedDays; i++)
    {
        do
        {
            current = current.AddDays(sign);
        }
        while (current.DayOfWeek == DayOfWeek.Saturday ||
            current.DayOfWeek == DayOfWeek.Sunday);
    }
    return current;
}

/// <summary>
/// Subtracts the given number of business days to the <see cref="DateTime"/>.
/// </summary>
/// <param name="current">The date to be changed.</param>
/// <param name="days">Number of business days to be subtracted.</param>
/// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns>
public static DateTime SubtractBusinessDays(this DateTime current, int days)
{
    return AddBusinessDays(current, -days);
}