我正尝试在客户在接下来的 7 天内过生日时收到提醒。
我已经用这段代码试过了:
public bool IsBirthdayImminent
{
get { return DateOfBirth != null && DateOfBirth.Value.Date >= DateTime.Today.Date.AddDays(-7); }
}
当然这是行不通的,因为日期与它的年份一起存储(比如 05/21/1980)并且它还会比较年份。所以这个查询永远不会是 true
- 好吧,如果你在接下来的 7 天内出生就不会。
如何修改此查询以忽略年份?
编辑:
好吧,查询本身完全没有问题。我的主要观点是处理闰年和 12 月 <-> 1 月左右的情况。
最佳答案
我建议使用以下代码。这包括 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发表在下面的评论中。
关于c# - 比较没有年份的 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16947949/