当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# DateTime.IsLeapYear()用法及代码示例


此方法返回指示是否指定的年份是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

参考:



相关用法


注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 DateTime.IsLeapYear() Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。