您好,我是 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/