我会建议使用下面的代码。这包括12月 - 1月和2月29日左右的情况。虽然您可能想要看一下并在2月28日正确的排除或排除给定的days
。
BirthdayImminent(new DateTime(1980, 1, 1), new DateTime(2012, 1, 2), 7); // false
BirthdayImminent(new DateTime(1980, 1, 1), new DateTime(2012, 12, 28), 7); // true
BirthdayImminent(new DateTime(1980, 2, 28), new DateTime(2012, 2, 21), 7); // true
private static bool BirthdayImminent(DateTime birthDate, DateTime referenceDate, int days)
{
DateTime birthdayThisYear = birthDate.AddYears(referenceDate.Year - birthDate.Year);
if (birthdayThisYear < referenceDate)
birthdayThisYear = birthdayThisYear.AddYears(1);
bool birthdayImminent = (birthdayThisYear - referenceDate).TotalDays <= days;
return birthdayImminent;
}
同时保留边缘案例记在Guvante张贴在下面的评论。
尝试:DateOfBirth.Value.Date> = DateTime.Today.Date.AddYears(DateOfBirth.Value.Date.Year - DateTime.Today.Date.Year).AddDays(-7) – NeverHopeless
规范化两个日期:复制的DOB值,并将年份设置为与当年相同。现在你会比较苹果和苹果。 – Icarus
@Idle_Mind可能没有闰年问题?例如,如果其中一个日期是1996年2月29日,并且您尝试将其设置为2013年2月29日,则可能无法获得理想的结果。多年来日期之间的其他差异也是如此。 – Servy