How to calculate number of leap years between two years in C#

Posted by Vlad Bezden on Stack Overflow See other posts from Stack Overflow or by Vlad Bezden
Published on 2011-01-03T19:16:11Z Indexed on 2011/01/03 19:53 UTC
Read the original article Hit count: 201

Filed under:
|
|

Hi All,

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about datetime