当客户在接下来的7天内过生日时,我正试图收到提醒.
我用这段代码尝试过:
public bool IsBirthdayImminent
{
get { return DateOfBirth != null && DateOfBirth.Value.Date >= DateTime.Today.Date.AddDays(-7); }
}
Run Code Online (Sandbox Code Playgroud)
当然这不起作用,因为日期与其年份一起存储(比如说是05/21/1980),它也比较了年份.所以这个查询永远不会true- 好吧,如果你在接下来的七天内出生,那就不行了.
如何修改此查询以忽略年份?
编辑:
好吧,查询本身根本不是问题.我的主要观点是处理闰年和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;
}
Run Code Online (Sandbox Code Playgroud)
还要记住边缘案例Guvante在下面的评论中发布.
| 归档时间: |
|
| 查看次数: |
5268 次 |
| 最近记录: |