How to calculate number of leap years between two years in C#
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.
You can do it with LINQ simply as bellow:
var leepYears = Enumerable.Range(startYear, endYear - startYear + 1)
.Count(x => DateTime.IsLeapYear(x));
This should perform much better for large spans of time:
public int LeapYearsBetween(int year1, int year2)
{
var y1 = new DateTime(year1, 1, 1);
var y2 = new DateTime(year2, 1, 1);
var nonLeapDays = 365 * (y2.Year - y1.Year);
var leapDays = (y2 - y1).Days - nonLeapDays;
return leapDays;
}
Note that this counts the earlier year if it is a leap year, but not the later year. You'll need to modify the function if you need different behavior.