How to calculate number of leap years between two

2020-03-01 08:28发布

Is there a better way to calculate number of leap years between two years. Assuming I have start date and end date.

I have my code, but I think there should be more elegant way.

calling code:

var numberOfLeapYears = NumberOfLeapYears(startDate.Year + 1, endDate.Year - 1);

function itself:

    private static int NumberOfLeapYears(int startYear, int endYear)
    {
        var counter = 0;

        for (var year = startYear; year <= endYear; year++)
            counter += DateTime.IsLeapYear(year) ? 1 : 0;

        return counter;
    }

So if I have startDate = "10/16/2006" and endDate = "4/18/2004" I should only have 1 leap year (2000) in result. Another words startDate's Year and endDate's year should not be calculated, only years in between.

Thanks in advance for your help.

7条回答
你好瞎i
2楼-- · 2020-03-01 08:57

Just another code with primitives types

    public static int CountLeapYears(int startYear, int endYear) 
    {
        int acc = 0;

        while (true)
        {
            if ((startYear % 4 == 0 && startYear % 100 != 0) || startYear % 400 == 0)
                acc++;
            if (startYear + 1 == endYear) break;
            startYear++;
        }

        return acc;
    }
查看更多
登录 后发表回答