c#如何计算一个月剩余的工作日

标签 c#

您好,我是 c# 的新手,一般来说我是编程的新手,我一直在尝试从调整其他人的代码中学习下面的代码,我已经更改了代码,因为我想计算剩余的工作日数在一个月内,但问题是代码运行了一个月中的天数,所以这个月有 29 天,但是当代码运行到 30 时代码错误我无法弄清楚要更改代码的哪一部分任何帮助都会很棒

    private void days()
    {

        //Monday to Friday are business days.
        var weekends = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday };
        DateTime testing = DateTime.Now;



        string month1 = testing.ToString("M ");
        string year1 = testing.ToString("yyyy");
        int month = Convert.ToInt32(month1);
        int year = Convert.ToInt32(year1);


        //Fetch the amount of days in your given month.
        int daysInMonth = DateTime.DaysInMonth(year, month);
        string daysleft = testing.ToString("d ");
        int daystoday = Convert.ToInt32(daysleft);

        //Here we create an enumerable from 1 to daysInMonth,
        //and ask whether the DateTime object we create belongs to a weekend day,
        //if it doesn't, add it to our IEnumerable<int> collection of days.
        IEnumerable<int> businessDaysInMonth = Enumerable.Range(daystoday, daysInMonth)
                                               .Where(d => !weekends.Contains(new DateTime(year, month, d).DayOfWeek));

        //Pretty smooth.

        int count = 0;
        foreach (var day in businessDaysInMonth)
        {
            count = count + 1;
        }
        textBox9.Text = count.ToString();


    }
}

最佳答案

public static IEnumerable<int> Range(int start, int count)

如您所见,第二个参数不是结束,而是计数。

你想要的计数可能是:daysInMonth - daystoday + 1

我会将您的代码重写为:

private static readonly DayOfWeek[] weekends = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday };

bool IsWorkDay(DateTime day)//Encapsulate in a function, to simplify dealing with holydays
{
    return !weekends.Contains(day.DayOfWeek);
}

int WorkDaysLeftInMonth(DateTime currentDate)
{
    var remainingDates = Enumerable.Range(currentDate.Day,DateTime.DaysInMonth(currentDate.Year,currentDate.Month)-currentDate.Day+1)
                        .Select(day=>new DateTime(currentDate.Year, currentDate.Month, day));
    return remainingDates.Count(IsWorkDay);
}

关于c#如何计算一个月剩余的工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9369029/

相关文章:

c# - 流利的断言 : Compare two numeric collections approximately

c# - 如何将 MySql 与 asp.net 身份结合使用以及 MVC 与 Microsoft ASP.NET 身份示例结合使用?

c# - 对于作为 Azure 应用服务 (P3) 托管的 .NET Core 2 Web api 的基准 RPS,我的期望应该是什么?

c# - LinkedIn OAuth 失败并显示 https_required 错误消息

c# - 如果对象被处理,则阻止 MouseLeave 触发器

c# - 跨多个网站共享用户控件

c# - 带有 MenuStrip 的透明表单背景?

c# - nTier + 运行时解析中的依赖注入(inject)

c# - 从另一个 Windows 服务启动和停止一个 Windows 服务

c# - Linq 错误 "Could not find an implementation of the query pattern for source type ' System.Linq.IQueryable“未找到加入”