如何在 C# 中使用 AddYears 方法获取 2 月 29 日

How to get 29 Feb using AddYears method in c#

我们使用一个每天运行的作业,并在一年前的一天执行一些操作。 实际上我们只是使用类似的东西:DateTime.UtcNow.AddYears(1)。 但是使用这种技术似乎不可能获得 2 月 29 日(例如 2020 年):

var target = new DateTime(2020, 2, 29);
bool result = (target == target.AddYears(-1).AddYears(1));//false

那么是否有可能以某种方式将 2 月 29 日作为目标?

没有。 Documentation 状态:

  • If value + DateTime.Year is also a leap year, the return value represents the leap day in that year. For example, if four years is added to February 29, 2012, the date returned is February 29, 2016.

  • If value + DateTime.Year is not a leap year, the return value represents the day before the leap day in that year. For example, if one year is added to February 29, 2012, the date returned is February 28, 2013.

这意味着如果您添加年份,您将始终得到 2 月 28 日。通过 AddYears 获得第 29 名的唯一方法是添加 4 的倍数。

不,这是 design

If the current instance represents the leap day in a leap year, the return value depends on the target date:

  • If value + DateTime.Year is also a leap year, the return value represents the leap day in that year. For example, if four years is added to February 29, 2012, the date returned is February 29, 2016.

  • If value + DateTime.Year is not a leap year, the return value represents the day before the leap day in that year. For example, if one year is added to February 29, 2012, the date returned is February 28, 2013.

2020 年 2 月 29 日之后的第 1 年应该是2021 年 2 月 28 日,因为它不是闰年。但在这种情况下,2021 年之后的所有年份都将作为 2 月 28 日计算。

除此之外,问问自己,"year" 对您来说意味着什么?一个月有多少天?一年有多少天?是365吗? 366?还是 wikipedia stated 365.2425?另外,我们说的是哪个日历?

框架、库等。并不像人们想象的那样工作。它们基于之前定义的一组规则工作。 .NET Framework 如此定义此规则。因此,当您将年份添加到 DateTime 实例时,他们决定的是月份部分必须保持不变,年份部分将根据添加多少年而改变,而日期部分必须是 有效一个。

正如 NibblyPig 所说,这是不可能的。但是,如果您实际上只是在寻找月底,那么您可以使用 new DateTime(year, month + 1, 0).AddDays(-1)

您可以通过 "the day before march 1st" 来欺骗系统。

存根:

DateTime today = DateTime.UtcNow
if (today.month == 2)
{
  if(today.day == 28 || today.day == 29)
  {
    today.AddDays(1).AddYears(1).AddDays(-1)
   }
}

这会将您的 2 月 28 日转换为 3 月 1 日的非闰年,增加一年,然后转到前一天。 如果明年也不是闰年,还是2月28日,如果明年是闰年,结果就是2月29日。

这还没有处理今年是闰年的情况,因为这段代码将 return 2 月 27 日改为

return 下一个 2 月 29 日的功能。也许有帮助。 使用系统;

public class Program
{
    public static DateTime NextTwentyNineFeb()
    {
        int year = DateTime.Now.Year;
        while(true){            
            try{
                var target = new DateTime(year, 2, 29);
                Console.WriteLine(target);
                return target;
            }
            catch
            {
                year++;
            }
        }
    }
}