如何减去工作日

本文关键字:工作日 何减去 | 更新日期: 2023-09-27 18:09:06

如何在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中看到的那样。

和一个没有循环的方法将是最有效的,就像你上面看到的。

如何减去工作日

见答案

(为方便起见,已将链接答案复制在下面)

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