c# - 在c#中从今天的日期开始查找下一个闰年

标签 c#

我想从今天开始找到下一个闰年。

例如,

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/

相关文章:

c# - 在 Windows CE 5 上安装我的程序

c# - LINQ 如何向这条语句添加一个 order by?

c# - CheckedListBox 对接无法正常工作

c# - .Net Maui/XAML QueryParameter 在 View 模型构造函数中为 NULL,但在 XAML 中可用,如何在 View 模型中访问它?

c# - CS0103 : The name 'CType' does not exist in the current context

c# - 是否可以缩短 XDocument 的 XDeclaration?

c# - ViewModel 和 Model 之间的 WPF 绑定(bind)

c# - 将 contextMenu 绑定(bind)到与 TreeView 不同的 View 模型

c# - asp.net 如何禁止浏览器保存 TextBox 以前的数据

c# - 使用 PostSharp 1.5 实现 INotifyPropertyChanged