こんにちは、私はc#
に新規です。一般的に私は、他の人々のコードを次のコードに適合させることから学びようとしています。 1月に作業日数が残っていますが、問題はコードが月の日数を超えて実行されるため、今月は29日ですが、コードとしてのコードエラーはに実行されます。私はどの部分すべてのヘルプは素晴らしいc#月に残っている稼働日数を計算する方法
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();
}
}
あなたは '自分でGetDaysInMonth'実装する必要はありません。フレームワークにはすでに 'DateTime.DaysInMonth'が含まれています。あなたのうるう年のロジックは醜いです(フレームワークコードを再度複製します)。モジュロ演算子を使用して任意の年の飛躍を計算することができます。 – CodesInChaos
私はそれを行う方法を表現するために5分で書いたが、それを行う最も効率的な方法ではなかった。 – user1054326