當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。