Phương thức DateTime.IsLeapYear() trong C# được dùng để kiểm tra năm được chỉ định có phải năm nhuận hay không. Giá trị trả về là boolean: TRUE nếu là năm nhuận, FALSE nếu không.
Cú pháp
Cú pháp như sau:
public static bool IsLeapYear(int y);
Tham số y là năm cần kiểm tra (ví dụ: 2010, 2016, 2019, v.v.).
Ví dụ 1 - Kiểm tra năm 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!");
}
}
}
Kết quả
Year = 2019 Not a Leap Year!
Ví dụ 2 - Năm ngoài phạm vi (gây ngoại lệ)
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!");
}
}
}
Kết quả (ngoại lệ)
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