SoFunction
Updated on 2025-03-06

C#, and SQL method to determine whether a specified year is a leap year

This article describes the method of judging whether a specified date is a leap year in c#, sql. Share it for your reference. The specific implementation method is as follows:

The C# code is as follows:

Copy the codeThe code is as follows:
public bool IsLeapYear(int year)
{
        if ((year < 1) || (year > 9999))
        {
throw new ArgumentOutOfRangeException("year", "The year must be a number from 1 to 9999.");
        }
        if ((year % 4) != 0)
        {
            return false;
        }
        if ((year % 100) == 0)
        {
            return ((year % 400) == 0);
        }
        return true;
}

:

Copy the codeThe code is as follows:
Public Function IsLeapYear(year As Integer) As Boolean
        If (year < 1) OrElse (year > 9999) Then
Throw New ArgumentOutOfRangeException("year", "The year must be a number from 1 to 9999.")
        End If
        If (year Mod 4) <> 0 Then
            Return False
        End If
        If (year Mod 100) = 0 Then
            Return ((year Mod 400) = 0)
        End If
        Return True
End Function

The sql code is as follows:
Copy the codeThe code is as follows:
udf_DaysInMonth_Ver2

CREATE FUNCTION [dbo].[udf_DaysInMonth]
(
    @Date DATETIME
)
RETURNS INT
AS
BEGIN
RETURN CASE WHEN MONTH(@Date) IN (1,3,5,7,8,10,12) THEN 31
            WHEN MONTH(@Date) IN (4,6,9,11) THEN 30
            ELSE CASE WHEN (YEAR(@Date) % 4 = 0 AND YEAR(@Date) % 100 <> 0) OR (YEAR(@Date) % 400  = 0)
                      THEN 29
                      ELSE 28
                 END
            END
END


In this way, I wrote all three instances directly in code form.

I hope this article will be helpful to everyone's C# and SQL programming.