C#/VB.NET/Sql中判断指定的年份是否为闰年代码

作者:袖梨 2022-06-25
 代码如下 复制代码

public bool IsLeapYear(int year)
    {
        if ((year < 1) || (year > 9999))
        {
            throw new ArgumentOutOfRangeException("year", "年份必须是从1至9999之间数字.");
        }

        if ((year % 4) != 0)
        {
            return false;
        }

        if ((year % 100) == 0)
        {
            return ((year % 400) == 0);
        }
        return true;
    }

VB.NET:

 代码如下 复制代码

Public Function IsLeapYear(year As Integer) As Boolean
        If (year < 1) OrElse (year > 9999) Then
            Throw New ArgumentOutOfRangeException("year", "年份必须是从1至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

sql

 代码如下 复制代码

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

这样我就就把三个实例都以代码形式直接写出来了。

相关文章

精彩推荐