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.
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With