Reputation: 211
I want to find the next leap year from today's date.
For ex.,
Date NextLeapDate
----- ------------
2016-01-01 2016-02-29
2016-05-24 2020-02-29
2017-02-03 2020-02-29
This is what I have so far to get the next leap year but it's getting me wrong value,
public int GetNextLeapYear(int year)
{
bool isLeapYear = false;
while (true)
{
if (DateTime.IsLeapYear(year))
{
isLeapYear = true;
}
else
{
year = year + 1;
GetNextLeapYear(year);
}
break;
}
return year;
}
Upvotes: 1
Views: 1889
Reputation: 847
To use recursion to find the next leap year, you can change your method like so.
public int GetNextLeapYear(int year)
{
if (!DateTime.IsLeapYear(year))
{
return GetNextLeapYear(year + 1);
}
return year;
}
Using recursion, you don't need the While loop, you just need to check to see if you need to continue or return the value. This also allows you to get rid of variables that are not needed. @poke answer is more complete counting for the actual month that you are in and such. I only answered this way to keep with using recursion like you had done.
Upvotes: 1
Reputation: 1379
Your current code is only a part of the program? The below code is copied from the question and changed with my suggestion edit (as well as other simplifications) to make it work correctly.
public int GetNextLeapYear(int year)
{
if (DateTime.IsLeapYear(year))
{
return year;
}
else
{
year = year + 1;
return GetNextLeapYear(year);
}
}
Upvotes: 2
Reputation: 387527
Something like this:
DateTime GetNextLeapDate (DateTime baseDate)
{
int year = baseDate.Year;
// start in the next year if we’re already in March
if (baseDate.Month > 2)
year++;
// find next leap year
while (!DateTime.IsLeapYear(year))
year++;
// get last of February
return new DateTime(year, 2, 29);
}
Note that we need to skip checking the current year if (and only if) the base date is already ahead of March (i.e. a possible leap day is already over). That way, we don’t get a result of February 29th, 2016 for e.g. today (time of this post).
Used like this, it returns the desired dates:
Console.WriteLine(GetNextLeapDate(new DateTime(2016, 01, 01))); // 2016-02-29
Console.WriteLine(GetNextLeapDate(new DateTime(2016, 05, 24))); // 2020-02-29
Console.WriteLine(GetNextLeapDate(new DateTime(2017, 02, 03))); // 2020-02-29
Upvotes: 6
Reputation: 836
You don't need recursion. Try this:
public int GetNextLeapYear(int year)
{
while (true)
{
if (DateTime.IsLeapYear(year))
{
return year;
}
year = year + 1;
}
}
Upvotes: 2