嗨,我是新手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();
}
}
Run Code Online (Sandbox Code Playgroud)
public static IEnumerable<int> Range(int start, int count)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,第二个参数不是结束,而是计数.
你想要的计数可能是: 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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2731 次 |
最近记录: |