此方法返回指示是否指定的年份是a年。在这里,年份始终被解释为公历中的年份。
句法:
public static bool IsLeapYear (int year);
返回值:如果year是a年,则此方法返回true ,否则返回false 。
异常:如果年份小于1或大于9999,则此方法将提供ArgumentOutOfRangeException。
下面的程序说明了上面讨论的方法的使用:
范例1:
// C# code to demonstrate the
// IsLeapYear(Int32) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// Checing the leap year between 2000 to 2019
for (int y = 2000; y <= 2019; y++)
{
// using method
if (DateTime.IsLeapYear(y))
{
Console.WriteLine("{0} is a Leap Year.", y);
}
else
{
Console.WriteLine("{0} is not a Leap Year.", y);
}
}
}
}
输出:
2000 is a Leap Year.
2001 is not a Leap Year.
2002 is not a Leap Year.
2003 is not a Leap Year.
2004 is a Leap Year.
2005 is not a Leap Year.
2006 is not a Leap Year.
2007 is not a Leap Year.
2008 is a Leap Year.
2009 is not a Leap Year.
2010 is not a Leap Year.
2011 is not a Leap Year.
2012 is a Leap Year.
2013 is not a Leap Year.
2014 is not a Leap Year.
2015 is not a Leap Year.
2016 is a Leap Year.
2017 is not a Leap Year.
2018 is not a Leap Year.
2019 is not a Leap Year.
范例2:
// C# code to demonstrate the
// IsLeapYear(Int32) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// using method
if (DateTime.IsLeapYear(9999))
{
Console.WriteLine("9999 is a Leap Year.");
}
else
{
Console.WriteLine("9999 is not a Leap Year.");
}
// using method will give an error
// as year's value is greater than
// 9999
if (DateTime.IsLeapYear(10000))
{
Console.WriteLine(" 10000 is a Leap Year.");
}
else {
Console.WriteLine("10000 is not a Leap Year.");
}
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: Year must be between 1 and 9999.
Parameter name: year
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.datetime.isleapyear?view=netframework-4.7.2