我建议使用以下代码。这包括 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的边缘情况。