我想从今天开始找到下一个闰年。
例如,
Date NextLeapDate
----- ------------
2016-01-01 2016-02-29
2016-05-24 2020-02-29
2017-02-03 2020-02-29
到目前为止,这是我获得下一个闰年的结果,但它让我得到了错误的值(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;
}
最佳答案
像这样的东西:
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);
}
请注意,如果(且仅当)基准日期已经早于 3 月(即可能的闰日已经结束),我们需要跳过检查当前年份。这样,我们就不会得到 2016 年 2 月 29 日的结果,例如今天(这篇文章的时间)。
像这样使用,它返回所需的日期:
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
关于c# - 在c#中从今天的日期开始查找下一个闰年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38337407/