C#의 DateTime.IsLeapYear() 메서드는 지정한 연도가 윤년(leap year)인지 여부를 확인하는 데 사용됩니다. 이 메서드는 불리언(Boolean) 값을 반환하며, 해당 연도가 윤년이면 TRUE, 그렇지 않으면 FALSE를 리턴합니다.
문법(Syntax)
DateTime.IsLeapYear() 메서드의 기본 문법은 다음과 같습니다.
public static bool IsLeapYear (int y);
여기서 매개변수 y는 윤년 여부를 검사할 연도를 의미합니다. 예를 들어 2010, 2016, 2019 등이 될 수 있습니다.
예제 1: 기본 사용법
다음은 DateTime.IsLeapYear() 메서드를 실제로 구현한 예제입니다.
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!
2019년은 4로 나누어 떨어지지 않는 평년이므로 "Not a Leap Year!"가 출력되는 것을 확인할 수 있습니다.
예제 2: 범위를 벗어난 연도 입력
이번에는 허용 범위를 벗어난 연도 값을 전달했을 때 어떤 일이 발생하는지 살펴보겠습니다.
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!");
}
}
}출력 결과
연도 값이 유효 범위(1~9999)를 초과하므로 실행 시 예외(Runtime Exception)가 발생합니다. 스택 트레이스(Stack Trace)에 다음과 같은 오류 메시지가 출력됩니다.
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
정리
DateTime.IsLeapYear() 메서드를 사용할 때는 반드시 1부터 9999 사이의 연도 값을 전달해야 합니다. 범위를 벗어난 값이 입력되면 ArgumentOutOfRangeException 예외가 발생하므로, 실무에서는 유효성 검사를 먼저 수행한 후 호출하는 것이 안전합니다.