Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 503
Vlad Bezden Avatar asked Jan 03 '11 19:01

Vlad Bezden


People also ask

How do you calculate a leap year between two years?

To check if a year is a leap year, divide the year by 4. If it is fully divisible by 4, it is a leap year. For example, the year 2016 is divisible 4, so it is a leap year, whereas, 2015 is not. However, Century years like 300, 700, 1900, 2000 need to be divided by 400 to check whether they are leap years or not.

How do you check a number is leap year or not?

Check if the number is evenly divisible by 400 to confirm a leap year. If a year is divisible by 100, but not 400, then it is not a leap year. If a year is divisible by both 100 and 400, then it is a leap year. For example, 1900 is evenly divisible by 100, but not 400 since it gives you a result of 4.75.

How many leap years are there between 2000 and 2100?

The complete list of leap years in the first half of the 21st century is therefore 2000, 2004, 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, and 2048.


2 Answers

You can count it using analytic approach. A year is a leap year if it can be divided by 4, but can't be divided by 100, except of case when it can be divided by 400. Assuming that you can count such number by following code:

static int LeapYearsBetween(int start, int end)
{
    System.Diagnostics.Debug.Assert(start < end);
    return LeapYearsBefore(end) - LeapYearsBefore(start + 1);
}

static int LeapYearsBefore(int year)
{
    System.Diagnostics.Debug.Assert(year > 0);
    year--;
    return (year / 4) - (year / 100) + (year / 400);
}

Some kind of math magic. It is much effective solution than using LINQ.

like image 74
Victor Haydin Avatar answered Sep 19 '22 14:09

Victor Haydin


You can do it with LINQ simply as bellow:

var leepYears = Enumerable.Range(startYear, endYear - startYear + 1)
                              .Count(x => DateTime.IsLeapYear(x));
like image 25
Saeed Amiri Avatar answered Sep 17 '22 14:09

Saeed Amiri