ある年がうるう年かどうかを判別するには、DateTimeの静的メソッドであるIsLeapYearメソッドを使うことが出来ます。 このメソッドは静的メソッドで、引数には年を表す数値を指定します。 次の例では、2010年〜2020年の各年について、その年がうるう年かどうかを調べて表示しています。
DateTime.IsLeapYearメソッドである年がうるう年かどうかを調べる
using System;
class Sample {
static void Main()
{
for (var year = 2010; year <= 2020; year++) {
// 2010年〜2020年の各年がうるう年かどうかを求める
Console.WriteLine("IsLeapYear({0}) : {1}", year, DateTime.IsLeapYear(year));
}
}
}
実行結果
IsLeapYear(2010) : False IsLeapYear(2011) : False IsLeapYear(2012) : True IsLeapYear(2013) : False IsLeapYear(2014) : False IsLeapYear(2015) : False IsLeapYear(2016) : True IsLeapYear(2017) : False IsLeapYear(2018) : False IsLeapYear(2019) : False IsLeapYear(2020) : True
DateTimeではグレゴリオ暦が使用されるため、IsLeapYearメソッドもグレゴリオ暦の暦法に従ってうるう年かどうかの判定が行われます。 グレゴリオ暦以外でのうるう年の判定を行う必要がある場合は、Calendarクラスを使います。