Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด DateTime.IsLeapYear() ใน C#

เมธอด DateTime.IsLeapYear() ใน C# ใช้สำหรับตรวจสอบว่าปีที่ระบุเป็นปีอธิกสุรทิน (leap year) หรือไม่ ค่าที่คืนกลับเป็น Boolean: true หากเป็นปีอธิกสุรทิน, false หากไม่ใช่

ไวยากรณ์

ไวยากรณ์มีดังนี้:

public static bool IsLeapYear (int y);

พารามิเตอร์ y คือปีที่ต้องการตรวจสอบ (เช่น 2010, 2016, 2019, เป็นต้น)

ตัวอย่าง

ตัวอย่างการตรวจสอบปี 2019:

using System; 
public class Demo { 
    public static void Main() { 
        int year = 2019; 
        Console.WriteLine("Year = " + year); 
        if (DateTime.IsLeapYear(year)){ 
            Console.WriteLine("Leap Year!"); 
        } else { 
            Console.WriteLine("Not a Leap Year!"); 
        } 
    } 
}

ผลลัพธ์

โค้ดจะแสดงผลดังนี้:

Year = 2019 
Not a Leap Year!

ตัวอย่างเพิ่มเติม

ตัวอย่างกับปีที่อยู่นอกช่วง (จะโยนข้อยกเว้น):

using System; 
public class Demo { 
    public static void Main() { 
        int year = 101910; 
        Console.WriteLine("Year = " + year); 
        if (DateTime.IsLeapYear(year)){ 
            Console.WriteLine("Leap Year!"); 
        } else { 
            Console.WriteLine("Not a Leap Year!"); 
        } 
    } 
}

ผลลัพธ์

โค้ดจะแสดงข้อผิดพลาด:

Year = 101910 
Run-time exception (line 11): Year must be between 1 and 9999. 
Parameter name: year 
Stack Trace: [System.ArgumentOutOfRangeException: Year must be between 1 and 9999. Parameter name: year] 
at System.DateTime.IsLeapYear(Int32 year) 
at Demo.Main() :line 11

หมายเหตุ: ปีต้องอยู่ในช่วง 1 ถึง 9999 เท่านั้น